Sorted Array: All Unique Pairs With a Given Sum
Arrays & HashingAuto-graded · 23 test casesLast updated
Tests whether a candidate can apply the two-pointer pattern on a sorted array to collect every distinct value pair that adds up to a target, without emitting duplicates.
Sorted Array: All Unique Pairs With a Given Sum
You are given a non-decreasing integer array nums and an integer target. Return every unique pair of values [a, b] where a <= b and a + b == target.
Two pairs are considered identical if they contain the same two values, regardless of how many times those values appear in nums. Each distinct value pair must appear exactly once in your output.
Your solution must use the two-pointer technique and run in O(n) time with O(1) extra space beyond the output list itself.
Output format
Return a list of two-element lists. Each inner list [a, b] satisfies a <= b and a + b == target. The pairs must appear in ascending order of a.
Constraints
0 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9-2 * 10^9 <= target <= 2 * 10^9numsis sorted in non-decreasing order- A pair
[a, a]is valid only when at least two separate positions innumsboth hold the valuea - If no valid pair exists, return an empty list
Examples
Example 1
Input: find_target_pairs([-5, -2, -1, 0, 1, 3, 4, 6], 2)
Output: [[-2, 4], [-1, 3]]
Example 2
Input: find_target_pairs([1, 1, 2, 2, 3, 3, 4, 4], 5)
Output: [[1, 4], [2, 3]]
Example 3
Input: find_target_pairs([0, 0, 0, 0], 0)
Output: [[0, 0]]
Hints
Hint 1
Place one pointer at the leftmost index and the other at the rightmost index. The sorted order means you can predict whether the current sum is too small, too large, or exactly right — and move accordingly.
Hint 2
When the two pointers land on a matching pair, you still need to advance both of them past every copy of each value before continuing. Skipping the whole run is what prevents the same value pair from appearing in your output more than once.
Hint 3
The case where both values in the pair are equal (e.g. [3, 3]) is handled automatically as long as you require the left pointer to stay strictly to the left of the right pointer — that condition guarantees two distinct positions exist in the array.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea
Because nums is sorted, placing one pointer at each end gives us a window whose sum we can steer deterministically:
- Sum too small → the left value is useless against every remaining right candidate (all of them are ≤ the current right value), so advance
left. - Sum too large → the right value is useless against every remaining left candidate, so retreat
right. - Sum exact → record the pair, then move both pointers.
The key deduplication step is to advance each pointer past the entire run of its current value whenever we act on it. This way, once a value pair is recorded (or discarded), no copy of either value can resurface to produce the same pair again.
Why it is correct
Elimination argument. If nums[left] + nums[right] < target, then nums[left] paired with any index ≤ right is also too small (those elements are no larger than nums[right]). So nums[left] cannot be part of any valid pair that still lies within the current window — every copy of it can be dropped. The symmetric argument handles the > target case.
Match case. When the sum equals target, the only partner for value a = nums[left] is target − a = nums[right]. Any remaining copy of a would again need b as its partner, which would duplicate the pair just recorded. Skipping both runs prevents this.
Boundary invariant. The condition left < right is checked before every read, so we never access out-of-bounds memory and we never emit a pair where both indices point at the same slot (which would require only one physical element to form the pair).
a == b pairs. A pair like [3, 3] requires two distinct positions holding 3. The left < right guard ensures they exist. With a single 3 in the array, the pointers would meet and the loop would stop without emitting it.
Complexity
- Time: O(n). Every inner
whilestep either incrementsleftor decrementsright. Since the pointers start at distancen − 1and the loop stops when they meet, at mostn − 1moves happen in total. - Space: O(1) auxiliary. Only a constant number of scalar variables are used. The output list itself can hold up to ⌊n/2⌋ pairs; that is counted as output space, not auxiliary memory.
Edge cases
| Situation | Outcome |
|---|---|
| Empty or single-element array | Loop body never executes; returns [] |
All elements identical (e.g. [2,2,2,2], target 4) | Exactly one pair [2,2] emitted |
| No valid pair exists | Pointers converge; returns [] |
Heavy duplication (e.g. [1,1,1,5,5,5], target 6) | One pair [1,5], found in linear time |
| Negative numbers or zero | No special handling needed; only ordering matters |
Reference solution
from typing import List
def find_target_pairs(nums: List[int], target: int) -> List[List[int]]:
result = []
left, right = 0, len(nums) - 1
while left < right:
total = nums[left] + nums[right]
if total < target:
# nums[left] is too small paired with anything at or before right;
# skip the entire run of this value
left_value = nums[left]
while left < right and nums[left] == left_value:
left += 1
elif total > target:
# nums[right] is too large paired with anything at or after left;
# skip the entire run of this value
right_value = nums[right]
while left < right and nums[right] == right_value:
right -= 1
else:
# Found a valid pair; record it, then skip both full runs so the
# same value pair is never appended again
left_value, right_value = nums[left], nums[right]
result.append([left_value, right_value])
while left < right and nums[left] == left_value:
left += 1
while left < right and nums[right] == right_value:
right -= 1
return result