The Wayback Machine - https://web.archive.org/web/20241225120418/https://www.geeksforgeeks.org/two-elements-whose-sum-is-closest-to-zero/
Open In App

Two Sum – Pair Closest to 0

Last Updated : 18 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an integer array of N elements. You need to find the maximum sum of two elements such that sum is closest to zero. This problem is a variation of standard 2 Sum problems.

Note: In Case if we have two of more ways to form sum of two elements closest to zero return the maximum sum.
Example:

Input: arr[] = {-8, 5, 2, -6}
Output: -1
Explanation: The min absolute sum pair is (5, -6)

Input: arr[] = {0, -8, -6, 3}
Output: 3
Explanation: We have a tie between (0, 3) and (-6, 3). We pick the max sum in this case which is 0+3

Naive – O(n^2) time and O(1) Space

We use the brute-force method that checks the sum of every possible pair of elements in the array and keeps track of the pair with the minimum absolute sum.

C++
#include <bits/stdc++.h>
using namespace std;

int minAbsSumPair(vector<int>& arr) {
  
    // Initialize the result with the sum 
    // of the first two elements
    int res = arr[0] + arr[1];

    // Consider every pair, find its sum and
    // update result if we get a smaller value
    for (int i = 0; i < arr.size() - 1; i++) {
        for (int j = i + 1; j < arr.size(); j++) {
            int sum = arr[i] + arr[j];
            if (abs(sum) < abs(res)) {
                res = sum;
            }
        }
    }
    return res;
}

int main() {
    vector<int> arr = { 1, 60, -10, 70, -80, 85 };
    cout << minAbsSumPair(arr);
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int minAbsSumPair(int arr[], int n) {
  
    // Initialize the result with the
    // sum of the first two elements
    int res = arr[0] + arr[1];

    // Consider every pair, find its sum and 
    // update result if we get a smaller value
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            int sum = arr[i] + arr[j];
            if (abs(sum) < abs(res)) {
                res = sum;
            }
        }
    }
    return res;
}

int main() {
    int arr[] = { 1, 60, -10, 70, -80, 85 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", minAbsSumPair(arr, n));
    return 0;
}
Java
import java.util.*;

class GfG {

    static int minAbsSumPair(int[] arr) {

        // Initialize the result with the sum 
        // of the first two elements
        int res = arr[0] + arr[1];

        // Consider every pair, find its sum and
        // update result if we get a smaller value
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                int sum = arr[i] + arr[j];
                if (Math.abs(sum) < Math.abs(res)) {
                    res = sum;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = { 1, 60, -10, 70, -80, 85 };
        System.out.println(minAbsSumPair(arr));
    }
}
Python
def min_abs_sum_pair(arr):
  
    # Initialize the result with the sum 
    # of the first two elements
    res = arr[0] + arr[1]

    # Consider every pair, find its sum and
    # update result if we get a smaller value
    for i in range(len(arr) - 1):
        for j in range(i + 1, len(arr)):
            sum = arr[i] + arr[j]
            if abs(sum) < abs(res):
                res = sum

    return res

arr = [1, 60, -10, 70, -80, 85]
print(min_abs_sum_pair(arr))
JavaScript
function minAbsSumPair(arr) {

    // Initialize the result with the sum 
    // of the first two elements
    let res = arr[0] + arr[1];

    // Consider every pair, find its sum and
    // update result if we get a smaller value
    for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            let sum = arr[i] + arr[j];
            if (Math.abs(sum) < Math.abs(res)) {
                res = sum;
            }
        }
    }
    return res;
}

const arr = [1, 60, -10, 70, -80, 85];
console.log(minAbsSumPair(arr));

Output
5

Time complexity: O(n2)
Auxiliary Space: O(1)

Using Sort and Binary Search – O(n Log n) time and O(1) Space

  1. Sort the array
  2. Traverse through every element arr[i] and do binary search in arr[i+1 … n-1] for an element x such that x + arr[i] has minimum absolute value.
  3. To do binary search if arr[i] + arr[mid] becomes 0, we return 0, else if arr[i] + arr[mid] becomes more than 0, we go the left side, else to the right side.
  4. We keep updating the result also during the process if we find a smaller absolute sun.
C++
#include <bits/stdc++.h>
using namespace std;

// Function to return the sum of the pair 
// with sum closest to 0
int closestPairSum(vector<int>& arr) {
  
    sort(arr.begin(), arr.end());    
    
    int n = arr.size();
    
    // Variable to store the closest sum
    int res = INT_MAX;

    // Iterate over the array
    for (int i = 0; i < n; i++) {
      
        // Consider current element as first 
        // element of the pair and find the
        // other element using binary search
        int x = arr[i];
        
        int left = i + 1, right = n - 1;

        while (left <= right) {
            int mid = (left + right) / 2;

            int curr = arr[mid] + x;

            // If exact pair is found
            if (curr == 0) {
                return 0; 
            }

            // Update res if the current pair is closer
            if (abs(curr) < abs(res)) {
                res = curr;
            }

            // If current is smaller than 0,
            // go to right side. Else on the
            // left side.
            if (curr < 0) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
    }

    return res;
}

// Driver program to test the above function
int main() {
    vector<int> arr = {-10, -3, 0, 5, 9, 20};
    int res = closestPairSum(arr);
    cout << "The closest sum to 0 is " << res << endl;
    return 0;
}
Java
import java.util.*;

class GfG {
    // Function to return the sum of the pair 
    // with sum closest to 0
    public static int closestPairSum(int[] arr) {
      
        Arrays.sort(arr);
      
        int n = arr.length;

        // Variable to store the closest sum
        int res = Integer.MAX_VALUE;

        // Iterate over the array
        for (int i = 0; i < n; i++) {
          
            // Consider current element as first 
            // element of the pair and find the
            // other element using binary search
            int x = arr[i];

            int left = i + 1, right = n - 1;

            while (left <= right) {
                int mid = (left + right) / 2;

                int curr = arr[mid] + x;

                // If exact pair is found
                if (curr == 0) {
                    return 0;
                }

                // Update res if the current pair is closer
                if (Math.abs(curr) < Math.abs(res)) {
                    res = curr;
                }

                // If current is smaller than 0,
                // go to right side. Else on the
                // left side.
                if (curr < 0) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }

        return res;
    }

    // Driver program to test the above function
    public static void main(String[] args) {
        int[] arr = {-10, -3, 0, 5, 9, 20};
        int res = closestPairSum(arr);
        System.out.println("The closest sum to 0 is " + res);
    }
}
Python
import sys

# Function to return the sum of the pair
# with sum closest to 0
def closestPairSum(arr):
    arr.sort()
   
    n = len(arr)

    # Variable to store the closest sum
    res = sys.maxsize

    # Iterate over the array
    for i in range(n):
        
        # Consider current element as first 
        # element of the pair and find the
        # other element using binary search
        x = arr[i]

        left, right = i + 1, n - 1

        while left <= right:
            mid = (left + right) // 2

            curr = arr[mid] + x

            # If exact pair is found
            if curr == 0:
                return 0

            # Update res if the current pair is closer
            if abs(curr) < abs(res):
                res = curr

            # If current is smaller than 0,
            # go to right side. Else on the
            # left side.
            if curr < 0:
                left = mid + 1
            else:
                right = mid - 1

    return res

# Driver program to test the above function
if __name__ == "__main__":
    arr = [-10, -3, 0, 5, 9, 20]
    res = closestPairSum(arr)
    print(f"The closest sum to 0 is {res}")
JavaScript
// Function to return the sum of the pair
// with sum closest to 0
function closestPairSum(arr) {
    arr.sort((x, y) => (x-y));
   
    let n = arr.length;

    // Variable to store the closest sum
    let res = Infinity;

    // Iterate over the array
    for (let i = 0; i < n; i++) {
        
        // Consider current element as first 
        // element of the pair and find the
        // other element using binary search
        let x = arr[i];

        let left = i + 1, right = n - 1;

        while (left <= right) {
            let mid = Math.floor((left + right) / 2);

            let curr = arr[mid] + x;

            // If exact pair is found
            if (curr === 0) {
                return 0;
            }

            // Update res if the current pair is closer
            if (Math.abs(curr) < Math.abs(res)) {
                res = curr;
            }

            // If current is smaller than 0,
            // go to right side. Else on the
            // left side.
            if (curr < 0) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
    }

    return res;
}

// Driver program to test the above function
const arr = [-10, -3, 0, 5, 9, 20];
const res = closestPairSum(arr);
console.log(`The closest sum to 0 is ${res}`);

Output
The closest sum to 0 is -1

The Best Approach – Sorting and Two Pointer – O(n Log n) time and O(1) Space

Sort the given array, try two pointer algorithm to find sum closest to zero, we adjust the pointer according to the current sum. We mainly increment left pointer when the current pair sum is negative and decrement the right pointer otherwise.

  • Sort the given array.
  • Initialize two pointers i and j at the beginning and end of the sorted array, respectively.
  • Initialize variables sum equal to arr[i] + arr[j] and diff equal to absolute of sum.
  • While i is less than j:
    • Calculate the current sum as arr[i] + arr[j].
    • If the current sum is equal to zero, return 0, as this is the closest possible sum.
    • If the absolute value of the current sum is less than the absolute value of diff, update diff and sum with the current sum.
    • If the absolute value of the current sum is equal to the absolute value of diff, update sum to be the maximum of the current sum and the previous sum.
    • If arr[i] + arr[j] is less than 0 then increment i by 1 else decrement j by 1.
  • After completing the iteration, return the final sum, which represents the maximum sum of two elements closest to zero.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

int closestToZero(vector<int>& arr) {
  
    // Sorting the vector in ascending order
    sort(arr.begin(), arr.end());

    int i = 0, j = arr.size() - 1;

    // Initializing sum with the first 
    // and last elements
    int sum = arr[i] + arr[j];

    // Initializing the result with 
    // the absolute value of the initial sum
    int diff = abs(sum);

    while (i < j) {
      
        // If we have zero sum, there's no 
        // result better. Hence, we return
        if (arr[i] + arr[j] == 0)
            return 0;

        // If we get a better result, we update the difference
        if (abs(arr[i] + arr[j]) < abs(diff)) {
            diff = abs(arr[i] + arr[j]);
            sum = arr[i] + arr[j];
        } else if (abs(arr[i] + arr[j]) == abs(diff)) {
          
            // If there are multiple pairs with the
            // same minimum absolute difference,
            // return the pair with the larger sum
            sum = max(sum, arr[i] + arr[j]);
        }

        // If the current sum is greater than
        // zero, we search for a smaller sum
        if (arr[i] + arr[j] > 0)
            j--;
      
        // Else, we search for a larger sum
        else
            i++;
    }
    return sum;
}

// Driver Code
int main() {
    vector<int> arr = { 1, 60, -10, 70, -80, 85 };
    cout << closestToZero(arr) << endl;
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Comparison function for qsort
int compare(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

int closestToZero(int arr[], int n) {
  
    // Sorting the array in ascending order
    qsort(arr, n, sizeof(int), compare);

    int i = 0, j = n - 1;

    // Initializing sum with the first and last elements
    int sum = arr[i] + arr[j];

    // Initializing the result with the 
    // absolute value of the initial sum
    int diff = abs(sum);

    while (i < j) {
      
        // If we have zero sum, there's no result
        // better. Hence, we return
        if (arr[i] + arr[j] == 0)
            return 0;

        // If we get a better result, we update the difference
        if (abs(arr[i] + arr[j]) < abs(diff)) {
            diff = abs(arr[i] + arr[j]);
            sum = arr[i] + arr[j];
        } else if (abs(arr[i] + arr[j]) == abs(diff)) {
          
            // If there are multiple pairs with the
            // same minimum absolute difference,
            // return the pair with the larger sum
            sum = (sum > arr[i] + arr[j]) ? sum : arr[i] + arr[j];
        }

        // If the current sum is greater
       // than zero, we search for a smaller sum
        if (arr[i] + arr[j] > 0)
            j--;
        // Else, we search for a larger sum
        else
            i++;
    }
    return sum;
}

// Driver Code
int main() {
    int arr[] = { 1, 60, -10, 70, -80, 85 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", closestToZero(arr, n));
    return 0;
}
Java
import java.util.Arrays;

public class ClosestToZero {

    public static int closestToZero(int[] arr)
    {
        // Sorting the array in ascending order
        Arrays.sort(arr);

        int i = 0, j = arr.length - 1;

        // Initializing sum with the first and last elements
        int sum = arr[i] + arr[j];

        // Initializing the result with the absolute value
        // of the initial sum
        int diff = Math.abs(sum);

        while (i < j) {
            // If we have zero sum, there's no result
            // better. Hence, we return 0.
            if (arr[i] + arr[j] == 0)
                return 0;

            // If we get a better result, we update the
            // difference
            if (Math.abs(arr[i] + arr[j])
                < Math.abs(diff)) {
                diff = (arr[i] + arr[j]);
                sum = arr[i] + arr[j];
            }
            else if (Math.abs(arr[i] + arr[j])
                     == Math.abs(diff)) {
                // If there are multiple pairs with the same
                // minimum absolute difference, return the
                // pair with the larger sum
                sum = Math.max(sum, arr[i] + arr[j]);
            }

            // If the current sum is greater than zero, we
            // search for a smaller sum
            if (arr[i] + arr[j] > 0)
                j--;
            // Else, we search for a larger sum
            else
                i++;
        }
        return sum;
    }

    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 1, 60, -10, 70, -80, 85 };
        System.out.println(closestToZero(arr));
    }
}
Python
def closest_to_zero(arr):
  
    # Sorting the array in ascending order
    arr.sort()

    i, j = 0, len(arr) - 1

    # Initializing sum with the first and last elements
    sum_val = arr[i] + arr[j]

    # Initializing the result with the absolute value
    # of the initial sum
    diff = abs(sum_val)

    while i < j:
      
        # If we have zero sum, there's no result
        # better. Hence, we return 0.
        if arr[i] + arr[j] == 0:
            return 0

        # If we get a better result, we update the
        # difference
        if abs(arr[i] + arr[j]) < abs(diff):
            diff = arr[i] + arr[j]
            sum_val = arr[i] + arr[j]
        elif abs(arr[i] + arr[j]) == abs(diff):
          
            # If there are multiple pairs with the same
            # minimum absolute difference, return the
            # pair with the larger sum
            sum_val = max(sum_val, arr[i] + arr[j])

        # If the current sum is greater than zero, we
        # search for a smaller sum
        if arr[i] + arr[j] > 0:
            j -= 1
        # Else, we search for a larger sum
        else:
            i += 1

    return sum_val


# Driver Code
arr = [1, 60, -10, 70, -80, 85]
print(closest_to_zero(arr))
JavaScript
function closestToZero(arr) {

    // Sorting the array in ascending order
    arr.sort((a, b) => a - b);

    let i = 0, j = arr.length - 1;

    // Initializing sum with the first and last elements
    let sum = arr[i] + arr[j];

    // Initializing the result with the absolute value
    // of the initial sum
    let diff = Math.abs(sum);

    while (i < j) {
    
        // If we have zero sum, there's no result
        // better. Hence, we return 0.
        if (arr[i] + arr[j] === 0)
            return 0;

        // If we get a better result, we update the
        // difference
        if (Math.abs(arr[i] + arr[j]) < Math.abs(diff)) {
            diff = arr[i] + arr[j];
            sum = arr[i] + arr[j];
        } else if (Math.abs(arr[i] + arr[j]) === Math.abs(diff)) {
        
            // If there are multiple pairs with the same
            // minimum absolute difference, return the
            // pair with the larger sum
            sum = Math.max(sum, arr[i] + arr[j]);
        }

        // If the current sum is greater than zero, we
        // search for a smaller sum
        if (arr[i] + arr[j] > 0)
            j--;
        // Else, we search for a larger sum
        else
            i++;
    }
    return sum;
}

// Example usage
let arr = [1, 60, -10, 70, -80, 85];
let result = closestToZero(arr);
console.log(result);

Output
5

Time Complexity: O(n log n)
Auxiliary Space: O(1)



Next Article

Similar Reads

three90RightbarBannerImg