Given a sorted array and a target, return all unique pairs of values that add up to the target, in ascending order.
ReportedSource: GeeksforGeeks interview experience: Google SDE-2 2025
Two pointers from both ends; move left if the sum is small, right if large; on a match record it and skip duplicates on both sides. O(n), O(1).
Constraints
- Input: first line n; second line n integers in non-decreasing order (the line is empty when n = 0); third line the target. Print each pair "x y" (x <= y) on its own line in ascending order; print -1 if there is no pair.
- 0 <= n <= 100000; values and target fit in 64-bit integers (absolute value at most 10^9 for values).
- A pair must use two different positions. Each distinct value pair is printed once.
Sample I/O
in: 6 1 2 3 4 5 6 7
out: 1 6 2 5 3 4
in: 6 1 1 2 2 3 3 4
out: 1 3 2 2
in: 3 1 2 3 100
out: -1
Sign up to run your code in the sandbox.
Sign up to run code and get an AI review
You can read and edit the challenge freely — running it in the sandbox and getting AI feedback need a free account.
Sign up freeHints
Reference solution
Two pointers. Because the array is sorted, start l at the left and r at the right.
- If
a[l] + a[r] < target, movelright (need a bigger sum). - If it is larger, move
rleft. - If it matches, record the pair, then skip every duplicate of
a[l]anda[r]so each pair appears once.
def pairs(a, target):
l, r, out = 0, len(a) - 1, []
while l < r:
s = a[l] + a[r]
if s < target:
l += 1
elif s > target:
r -= 1
else:
out.append((a[l], a[r]))
lv, rv = a[l], a[r]
while l < r and a[l] == lv: l += 1
while l < r and a[r] == rv: r -= 1
return out
Complexity. O(n) time, O(1) extra space. Pairs come out in ascending order of the first element automatically.
Follow-ups. Unsorted input (hash set, or sort first for O(n log n)); count pairs instead of listing them; 3Sum (fix one element and run this inside).