2 Sum - Pair Sum Closest to Target
Last Updated :
28 Dec, 2024
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, [22, 30] 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
4 Sum - Quadruplet Sum Closest to Target
Given an array arr[] of n integers and an integer target, the task is to find a quadruplet in arr[] whose sum is closest to target.Note: There may be multiple quadruplets with sum closest to the target, return any one of them.Examples:Input: arr[] = {4, 5, 3, 4, 1, 2}, target = 13Output: {4, 5, 3, 1
15 min read
3 Sum - Triplet Sum Closest to Target
Given an array arr[] of n integers and an integer target, the task is to find the sum of triplets such that the sum is closest to target. Note: If there are multiple sums closest to target, print the maximum one.Examples:Input: arr[] = [-1, 2, 2, 4], target = 4Output: 5Explanation: All possible trip
14 min read
Two Sum - Pair Closest to 0
Given an integer array arr[], the task is to find the maximum sum of two elements such that sum is closest to zero. Note: In case if we have two of more ways to form sum of two elements closest to zero return the maximum sum.Examples:Input: arr[] = [-8, 5, 2, -6]Output: -1Explanation: The min absolu
15+ min read
2 Sum - Pair Sum Closest to Target using Binary Search
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 ar
10 min read
Find the Closest Subsequence Sum to Target
Given an integer array arr[] and an integer target. The task is to find a subsequence of arr such that the absolute difference between the sum of its elements and target is minimized. Return the minimum possible value of abs(sum - target). Note: Subsequence of an array is an array formed by removing
5 min read
Count Pairs With Sum Less Than Target
Given an array arr[] and an integer target, the task is to find the count of pairs whose sum is strictly less than given target.Examples:Input: arr[] = [7, 2, 5, 3], target = 8Output: 2 Explanation: There are 2 pairs with sum less than 8: (2, 5) and (2, 3). Input: arr[] = [5, 2, 3, 2, 4, 1], target
15+ min read
Find the Sub-array with sum closest to 0
Given an array of both positive and negative numbers, the task is to find out the subarray whose sum is closest to 0. There can be multiple such subarrays, we need to output just 1 of them. Examples: Input : arr[] = {-1, 3, 2, -5, 4} Output : 1, 3 Subarray from index 1 to 3 has sum closest to 0 i.e.
13 min read
K Closest Points to a given Target point
Given a list of points on the 2-D plane arr[][], a given point target, and an integer K. The task is to find K closest points to the target from the given list of points. Note: The distance between two points on a plane is the Euclidean distance. Examples: Input: points = [[3, 3], [5, -1], [-2, 4]],
6 min read
2 Sum - Count pairs with given sum
Given an array arr[] of n integers and a target value, the task is to find the number of pairs of integers in the array whose sum is equal to target.Examples: Input: arr[] = {1, 5, 7, -1, 5}, target = 6Output: 3Explanation: Pairs with sum 6 are (1, 5), (7, -1) & (1, 5). Input: arr[] = {1, 1, 1,
9 min read
Two Sum - Pair with given Sum
Given an array arr[] of n integers and a target value, the task is to find whether there is a pair of elements in the array whose sum is equal to target. This problem is a variation of 2Sum problem.Examples: Input: arr[] = [0, -1, 2, -3, 1], target = -2Output: trueExplanation: There is a pair (1, -3
15+ min read