Given a sorted integer array, find a pair in it having an absolute minimum sum.

For example,

Input:  A = [-6, -5, -3, 0, 2, 4, 9]
 
Output: Pair is (-5, 4)
 
(-5, 4) = abs(-5 + 4) = abs(-1) = 1, which is minimum among all pairs.

Practice this problem

The idea is to maintain search space by maintaining two indexes (low and high) that initially points to two endpoints of the array. Then loop if low is less than the high index and reduce the search space arr[low…high] at each iteration of the loop by comparing the sum of elements present at index low and high with 0. We increment index low if the sum is less than the 0; otherwise, decrement index high if the sum is more than the 0. We also maintain the minimum absolute difference among all pairs present at low and high index.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Pair found (-5, 4)

Java


Download  Run Code

Output:

Pair found (-5, 4)

Python


Download  Run Code

Output:

Pair found (-5, 4)

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input.