KatInterview

Sorted Array: All Unique Pairs With a Given Sum

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingtwo-pointerssortingdeduplication

Last 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^9
  • nums is sorted in non-decreasing order
  • A pair [a, a] is valid only when at least two separate positions in nums both hold the value a
  • 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.