Find Pair of Integers with Sum Nearest to Zero
Heaps, Sorting & SearchAuto-graded · 19 test casesLast updated
Find a pair of distinct elements in an array whose sum has the smallest absolute value, breaking ties deterministically.
Given an array of integers a containing at least two elements, select a pair of distinct indices $(i, j)$ with $i < j$ such that the absolute value of their sum, $|a[i] + a[j]|$, is minimized.
Return the chosen pair as a list of two elements $[x, y]$ in non-decreasing order (i.e., $x \le y$).
Tie-Breaking Rule
If multiple pairs of distinct elements yield the same minimum absolute sum, select the pair $[x, y]$ (where $x \le y$) that is lexicographically smallest. That is, prioritize smaller values of $x$, and if $x$ is equal, prioritize smaller values of $y$.
Constraints
- $2 \le \text{len}(a) \le 10^5$
- $-10^9 \le a[i] \le 10^9$ for all $i$
Examples
Example 1
Input: find_pair_sum_closest_to_zero([13, -7, 6, 2, -10])
Output: [-7, 6]
Example 2
Input: find_pair_sum_closest_to_zero([1, 60, -10, 70, -80, 85])
Output: [-80, 85]
Example 3
Input: find_pair_sum_closest_to_zero([-5, 5, 1, -1])
Output: [-5, 5]
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To minimize $|x + y|$, for any chosen value $x$, the ideal partner $y$ is $-x$.
- Sort the array: Sorting takes $O(n \log n)$ time and brings numbers with similar values next to each other.
- Binary Search for Partners: Iterate through each element
values[i]. Search for the ideal partner $-values[i]$ in the subarray to the right (indices $j > i$). Usingbisect_leftgives the insertion indexpos. - Evaluate Candidates: The elements closest to $-values[i]$ will be at index
pos - 1and indexpos. For each valid index $j > i$, form the ordered pair(values[i], values[j]). - Compare Pairs: Use a comparison tuple key:
(abs(sum), (x, y)). Becausex <= y, evaluating candidate pairs using standard tuple ordering naturally enforces both the minimum absolute sum criterion and the lexicographical tie-breaking rule.
Complexity
- Time Complexity: $O(n \log n)$ to sort the array and perform $n$ binary searches of cost $O(\log n)$.
- Space Complexity: $O(n)$ to store the sorted copy of the input array.
Reference Solution
from bisect import bisect_left
from typing import List
def find_pair_sum_closest_to_zero(a: List[int]) -> List[int]:
values = sorted(a)
best_pair = None
best_key = None
for i, value in enumerate(values[:-1]):
target = -value
pos = bisect_left(values, target, i + 1)
for j in (pos - 1, pos):
if j <= i or j >= len(values):
continue
pair = (value, values[j])
key = (abs(pair[0] + pair[1]), pair)
if best_key is None or key < best_key:
best_key = key
best_pair = pair
return list(best_pair)