KatInterview

Find Pair of Integers with Sum Nearest to Zero

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searcharraysbinary-searchsorting

Last 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]