Open In App

2 Sum - Pair Sum Closest to Target

Last Updated : 28 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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]);

Output
2 7

[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]);

Output
2 7

Next Article

Similar Reads