2 Sum - Pair Sum Closest to Target
Last Updated :
23 Jul, 2025
Given an array arr[] of n integers and an integer target, the task is to find a pair in arr[] such that it’s sum is closest to target.
Note: Return the pair in sorted order and if there are multiple such pairs return the pair with maximum absolute difference. If no such pair exists return an empty array.
Examples:
Input: arr[] = [10, 30, 20, 5], target = 25
Output: [5, 20]
Explanation: Out of all the pairs, [5, 20] has sum = 25 which is closest to 25.
Input: arr[] = [5, 2, 7, 1, 4], target = 10
Output: [2, 7]
Explanation: As (4, 7) and (2, 7) both are closest to 10, but absolute difference of (2, 7) is 5 and (4, 7) is 3. Hence,[2, 7] has maximum absolute difference and closest to target.
Input: arr[] = [10], target = 10
Output: []
Explanation: As the input array has only 1 element, return an empty array.
[Naive Approach] Explore all possible pairs - O(n^2) Time and O(1) Space
A simple solution is to consider every pair and keep track of the closest pair (the absolute difference between pair sum and target is minimum). If two pairs are equally close to target then pick the one where the elements are farther apart (i.e., have the largest difference between them). Finally, print the closest pair.
C++
// C++ Code to find the pair with sum closest to target by
// exploring all the pairs
#include <iostream>
#include <limits.h>
#include <vector>
using namespace std;
vector<int> sumClosest(vector<int> &arr, int target) {
int n = arr.size();
vector<int> res;
int minDiff = INT_MAX;
// Generating all possible pairs
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int currSum = arr[i] + arr[j];
int currDiff = abs(currSum - target);
// if currDiff is less than minDiff, it indicates
// that this pair is closer to the target
if (currDiff < minDiff) {
minDiff = currDiff;
res = { min(arr[i], arr[j]), max(arr[i], arr[j]) };
}
// if currDiff is equal to minDiff, find the one with
// largest absolute difference
else if (currDiff == minDiff &&
(res[1] - res[0]) < abs(arr[i] - arr[j])) {
res = { min(arr[i], arr[j]), max(arr[i], arr[j]) };
}
}
}
return res;
}
int main() {
vector<int> arr = {5, 2, 7, 1, 4};
int target = 10;
vector<int> res = sumClosest(arr, target);
if(res.size() > 0)
cout << res[0] << " " << res[1];
return 0;
}
C
// C Code to find the pair with sum closest to target by
// exploring all the pairs
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
// Function to find the minimum and maximum between two values
int min(int a, int b) {
return (a < b) ? a : b;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
// Function to find the pair with sum closest to target
int* sumClosest(int arr[], int n, int target) {
// If there are fewer than 2 elements, return NULL
if (n < 2) {
return NULL;
}
static int res[2];
int minDiff = INT_MAX;
// Generating all possible pairs
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int currSum = arr[i] + arr[j];
int currDiff = abs(currSum - target);
// if currDiff is less than minDiff, it indicates
// that this pair is closer to the target
if (currDiff < minDiff) {
minDiff = currDiff;
res[0] = min(arr[i], arr[j]);
res[1] = max(arr[i], arr[j]);
}
// if currDiff is equal to minDiff, find the one
// with the largest difference
else if (currDiff == minDiff &&
(res[1] - res[0]) < abs(arr[i] - arr[j])) {
res[0] = min(arr[i], arr[j]);
res[1] = max(arr[i], arr[j]);
}
}
}
return res;
}
int main() {
int arr[] = {5, 2, 7, 1, 4};
int target = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int* res = sumClosest(arr, n, target);
if (res != NULL)
printf("%d %d\n", res[0], res[1]);
else
printf("-1");
return 0;
}
Java
// Java Code to find the pair with sum closest to target by
// exploring all the pairs
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class GfG {
static List<Integer> sumClosest(int[] arr, int target) {
int n = arr.length;
List<Integer> res = new ArrayList<>();
int minDiff = Integer.MAX_VALUE;
// Generating all possible pairs
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int currSum = arr[i] + arr[j];
int currDiff = Math.abs(currSum - target);
// if currDiff is less than minDiff, it indicates
// that this pair is closer to the target
if (currDiff < minDiff) {
minDiff = currDiff;
res = Arrays.asList(Math.min(arr[i], arr[j]),
Math.max(arr[i], arr[j]));
}
// if currDiff is equal to minDiff, find the one with
// largest absolute difference
else if (currDiff == minDiff &&
(res.get(1) - res.get(0)) < Math.abs(arr[i] - arr[j])) {
res = Arrays.asList(Math.min(arr[i], arr[j]),
Math.max(arr[i], arr[j]));
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {5, 2, 7, 1, 4};
int target = 10;
List<Integer> res = sumClosest(arr, target);
if(res.size() > 0)
System.out.println(res.get(0) + " " + res.get(1));
}
}
Python
# Python Code to find the pair with sum closest to target by
# exploring all the pairs
import sys
def sumClosest(arr, target):
n = len(arr)
res = []
minDiff = sys.maxsize
# Generating all possible pairs
for i in range(n - 1):
for j in range(i + 1, n):
currSum = arr[i] + arr[j]
currDiff = abs(currSum - target)
# if currDiff is less than minDiff, it indicates
# that this pair is closer to the target
if currDiff < minDiff:
minDiff = currDiff
res = [min(arr[i], arr[j]), max(arr[i], arr[j])]
# if currDiff is equal to minDiff, find the one with
# largest absolute difference
elif currDiff == minDiff and \
(res[1] - res[0]) < abs(arr[i] - arr[j]):
res = [min(arr[i], arr[j]), max(arr[i], arr[j])]
return res
if __name__ == "__main__":
arr = [5, 2, 7, 1, 4]
target = 10
res = sumClosest(arr, target)
if len(res) > 0:
print(res[0], res[1])
C#
// C# Code to find the pair with sum closest to target by
// exploring all the pairs
using System;
using System.Collections.Generic;
class GfG {
static List<int> sumClosest(int[] arr, int target) {
int n = arr.Length;
List<int> res = new List<int>();
int minDiff = int.MaxValue;
// Generating all possible pairs
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int currSum = arr[i] + arr[j];
int currDiff = Math.Abs(currSum - target);
// if currDiff is less than minDiff, it indicates
// that this pair is closer to the target
if (currDiff < minDiff) {
minDiff = currDiff;
res = new List<int> { Math.Min(arr[i], arr[j]),
Math.Max(arr[i], arr[j]) };
}
// if currDiff is equal to minDiff, find the one with
// largest absolute difference
else if (currDiff == minDiff &&
(res[1] - res[0]) < Math.Abs(arr[i] - arr[j])) {
res = new List<int> { Math.Min(arr[i], arr[j]),
Math.Max(arr[i], arr[j]) };
}
}
}
return res;
}
static void Main(string[] args) {
int[] arr = { 5, 2, 7, 1, 4 };
int target = 10;
List<int> res = sumClosest(arr, target);
if(res.Count > 0)
Console.WriteLine(res[0] + " " + res[1]);
}
}
JavaScript
// JavaScript Code to find the pair with sum closest to target
// by exploring all the pairs
function sumClosest(arr, target) {
let n = arr.length;
let res = [];
let minDiff = Number.MAX_SAFE_INTEGER;
// Generating all possible pairs
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
let currSum = arr[i] + arr[j];
let currDiff = Math.abs(currSum - target);
// if currDiff is less than minDiff, it indicates
// that this pair is closer to the target
if (currDiff < minDiff) {
minDiff = currDiff;
res = [Math.min(arr[i], arr[j]), Math.max(arr[i], arr[j])];
}
// if currDiff is equal to minDiff, find the one with
// largest absolute difference
else if (currDiff === minDiff &&
(res[1] - res[0]) < Math.abs(arr[i] - arr[j])) {
res = [Math.min(arr[i], arr[j]), Math.max(arr[i], arr[j])];
}
}
}
return res;
}
// Driver Code
let arr = [5, 2, 7, 1, 4];
let target = 10;
let res = sumClosest(arr, target);
if(res.length > 0)
console.log(res[0] + " " + res[1]);
[Better Approach] Binary Search - O(2*nlogn) Time and O(1) Space
The idea is to sort the array and use binary search to find the second element in a pair. First, iterate over the array and for each element arr[i], binary search on the remaining array for the element closest to its complement, that is (target - arr[i]). While searching, we can have three cases:
- arr[mid] == complement: we have found an element which can pair with arr[i] to give pair sum = target.
- arr[mid] < complement: we need to search for a greater element, so update lo = mid + 1.
- arr[mid] > complement: we need to search for a lesser element, so update hi = mid - 1.
To know more about the implementation please refer to 2 Sum - Pair Sum Closest to Target using Binary Search.
[Expected Approach] Two Pointer Technique - O(nlogn+n) Time and O(1) Space
The idea is to sort the array and use Two Pointer Technique to find the pair with sum closest to target. Initialize a pointer left to the beginning of the array and another pointer right to the end of the array. Now, compare the sum at both the pointers to find the pair sum closest to target:
- If arr[left] + arr[right] < target: We need to increase the pair sum, so move left to higher value.
- If arr[left] + arr[right] > target: We need to decrease the pair sum, so move right to smaller value.
- If arr[left] + arr[right] == target: We have found a pair with sum = target, so we can return the pair.
Note: In this approach, we don't need to separately handle the case when there is a tie between pairs and we need to select the one with maximum absolute difference. This is because we are selecting the first element of the pair in increasing order, so if we have a tie between two pairs, we can always choose the first pair.
C++
// C++ Program to find pair with sum closest to target
// using Two Pointer Technique
#include <bits/stdc++.h>
using namespace std;
// function to return the pair with sum closest to target
vector<int> sumClosest(vector<int> &arr, int target) {
int n = arr.size();
sort(arr.begin(), arr.end());
vector<int> res;
int minDiff = INT_MAX;
int left = 0, right = n - 1;
while (left < right) {
int currSum = arr[left] + arr[right];
// Check if this pair is closer than the closest
// pair so far
if (abs(target - currSum) < minDiff) {
minDiff = abs(target - currSum);
res = {arr[left], arr[right]};
}
// If this pair has less sum, move to greater values
if (currSum < target)
left++;
// If this pair has more sum, move to smaller values
else if (currSum > target)
right--;
// If this pair has sum = target, return it
else
return res;
}
return res;
}
int main() {
vector<int> arr = {5, 2, 7, 1, 4};
int target = 10;
vector<int> res = sumClosest(arr, target);
if(res.size() > 0)
cout << res[0] << " " << res[1];
return 0;
}
C
// C Program to find pair with sum closest to target
// using Two Pointer Technique
#include <stdio.h>
#include <limits.h>
// Function to compare elements for sorting
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
// function to return the pair with sum closest to target
int* sumClosest(int arr[], int n, int target) {
// Handle the case when n < 2
if (n < 2) {
return NULL;
}
int* res = (int*)malloc(2 * sizeof(int));
qsort(arr, n, sizeof(int), compare);
int minDiff = INT_MAX;
int left = 0, right = n - 1;
while (left < right) {
int currSum = arr[left] + arr[right];
// Check if this pair is closer than the closest
// pair so far
if (abs(target - currSum) < minDiff) {
minDiff = abs(target - currSum);
res[0] = arr[left];
res[1] = arr[right];
}
// If this pair has less sum, move to greater values
if (currSum < target)
left++;
// If this pair has more sum, move to smaller values
else if (currSum > target)
right--;
// If this pair has sum = target, return it
else
return res;
}
return res;
}
int main() {
int arr[] = {5, 2, 7, 1, 4};
int target = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int* res = sumClosest(arr, n, target);
if (res != NULL)
printf("%d %d\n", res[0], res[1]);
return 0;
}
Java
// Java Program to find pair with sum closest to target
// using Two Pointer Technique
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class GfG {
// function to return the pair with sum closest to target
static List<Integer> sumClosest(int[] arr, int target) {
int n = arr.length;
Arrays.sort(arr);
List<Integer> res = new ArrayList<>();
int minDiff = Integer.MAX_VALUE;
int left = 0, right = n - 1;
while (left < right) {
int currSum = arr[left] + arr[right];
// Check if this pair is closer than the closest
// pair so far
if (Math.abs(target - currSum) < minDiff) {
minDiff = Math.abs(target - currSum);
res = Arrays.asList(arr[left], arr[right]);
}
// If this pair has less sum, move to greater values
if (currSum < target)
left++;
// If this pair has more sum, move to smaller values
else if (currSum > target)
right--;
// If this pair has sum = target, return it
else
return res;
}
return res;
}
public static void main(String[] args) {
int[] arr = {5, 2, 7, 1, 4};
int target = 10;
List<Integer> res = sumClosest(arr, target);
if(res.size() > 0)
System.out.println(res.get(0) + " " + res.get(1));
}
}
Python
# Python Program to find pair with sum closest to target
# using Two Pointer Technique
# function to return the pair with sum closest to target
def sumClosest(arr, target):
n = len(arr)
arr.sort()
res = []
minDiff = float('inf')
left = 0
right = n - 1
while left < right:
currSum = arr[left] + arr[right]
# Check if this pair is closer than the closest
# pair so far
if abs(target - currSum) < minDiff:
minDiff = abs(target - currSum)
res = [arr[left], arr[right]]
# If this pair has less sum, move to greater values
if currSum < target:
left += 1
# If this pair has more sum, move to smaller values
elif currSum > target:
right -= 1
# If this pair has sum = target, return it
else:
return res
return res
if __name__ == "__main__":
arr = [5, 2, 7, 1, 4]
target = 10
res = sumClosest(arr, target)
if len(res) > 0:
print(res[0], res[1])
C#
// C# Program to find pair with sum closest to target
// using Two Pointer Technique
using System;
using System.Collections.Generic;
class GfG {
// function to return the pair with sum closest to target
static List<int> sumClosest(int[] arr, int target) {
int n = arr.Length;
Array.Sort(arr);
List<int> res = new List<int>();
int minDiff = int.MaxValue;
int left = 0, right = n - 1;
while (left < right) {
int currSum = arr[left] + arr[right];
// Check if this pair is closer than the closest
// pair so far
if (Math.Abs(target - currSum) < minDiff) {
minDiff = Math.Abs(target - currSum);
res = new List<int> { arr[left], arr[right] };
}
// If this pair has less sum, move to greater values
if (currSum < target)
left++;
// If this pair has more sum, move to smaller values
else if (currSum > target)
right--;
// If this pair has sum = target, return it
else
return res;
}
return res;
}
static void Main() {
int[] arr = { 5, 2, 7, 1, 4 };
int target = 10;
List<int> res = sumClosest(arr, target);
if(res.Count > 0)
Console.WriteLine(res[0] + " " + res[1]);
}
}
JavaScript
// JavaScript Program to find pair with sum closest to target
// using Two Pointer Technique
// function to return the pair with sum closest to target
function sumClosest(arr, target) {
let n = arr.length;
arr.sort((a, b) => a - b);
let res = [];
let minDiff = Number.MAX_VALUE;
let left = 0, right = n - 1;
while (left < right) {
let currSum = arr[left] + arr[right];
// Check if this pair is closer than the closest
// pair so far
if (Math.abs(target - currSum) < minDiff) {
minDiff = Math.abs(target - currSum);
res = [arr[left], arr[right]];
}
// If this pair has less sum, move to greater values
if (currSum < target)
left++;
// If this pair has more sum, move to smaller values
else if (currSum > target)
right--;
// If this pair has sum = target, return it
else
return res;
}
return res;
}
// Driver Code
let arr = [5, 2, 7, 1, 4];
let target = 10;
let res = sumClosest(arr, target);
if (res.length > 0)
console.log(res[0] + " " + res[1]);
Similar Reads
Basics & Prerequisites
Data Structures
Array Data Structure GuideIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem