VOOZH about

URL: https://www.geeksforgeeks.org/dsa/two-elements-whose-sum-is-closest-to-zero/

⇱ Pair Sum Closest to 0 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Pair Sum Closest to 0

Last Updated : 19 Apr, 2026

Given an integer array arr[], find the sum of any two elements whose sum is closest to zero.

Note: In case if we have two ways to form sum closest to zero, return the maximum sum among them.

Examples:

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

Input: arr[] = [-7, 4, 1, -2]
Output: -1
Explanation: The min absolute sum pair is (1, -2).

[Naive Approach] Check Every Possible Pair - O(n^2) Time and O(1) Space

The idea is to use the naive 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.


Output
3

[Better Approach] Using Sorting + Binary Search - O(nlog(n)) Time and O(1) Space

The idea is to find the pair whose sum is closest to zero by sorting the array and using binary search for efficient lookup. For each element, we search for its closest complement using binary search, updating the closest sum found so far. If an exact zero sum is found, we return immediately.

Steps to implement the above idea:

  • Sort the array to enable binary search.
  • Iterate through each element and fix it as the first element of the pair.
  • Use binary search to find the closest second element.
  • Update the closest sum if the current pair gives a smaller absolute sum.
  • Return 0 if an exact zero sum pair is found.
  • Return the closest sum after checking all pairs.

Output
3

[Expected Approach] Using Sorting + Two Pointer - O(nlog(n)) Time and O(1) Space

The idea is to sort the array first and use two pointers, one at the leftmost (smallest) and the other at the rightmost (largest) element. We calculate their sum and check if it's closer to zero than our current best sum. If we find a sum of zero, we return immediately. Otherwise, we adjust the pointers based on whether the sum is positive (move right pointer left) or negative (move left pointer right).

Steps to implement the above idea:

  • Sort the array in ascending order.
  • Initialize two pointers: one at the start and one at the end.
  • Initialize variables to store the closest sum and its absolute difference.
  • Iterate while left pointer is less than right pointer.
  • Update the closest sum if the current sum is closer to zero.
  • Move the left pointer right if the sum is negative; else, move the right pointer left.



Output
3


Comment