Find all pairs summing to target in sorted array
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates skills in array manipulation, handling duplicates, and algorithmic efficiency with attention to time and space complexity analysis.
Constraints
- 0 <= len(nums) <= 10^5
- nums is sorted in non-decreasing order
- -10^9 <= nums[i], target <= 10^9
- Return index pairs [i, j] with i < j
- Each distinct value-pair must appear at most once
Examples
Input: ([1, 2, 3, 4, 5], 6)
Expected Output: [[0, 4], [1, 3]]
Explanation: 1+5=6 -> [0,4]; 2+4=6 -> [1,3]; 3 alone (middle) cannot pair with itself.
Input: ([1, 1, 2, 2, 3, 3], 4)
Expected Output: [[0, 5], [2, 3]]
Explanation: Value pair (1,3) recorded once as [0,5]; value pair (2,2) recorded once as [2,3].
Hints
- Because the array is sorted, you can place one pointer at the start and one at the end and move them toward each other.
- If the current sum is too small, advance the left pointer; if too large, retreat the right pointer; if equal, record the pair.
- After recording a match, skip past all equal values on both sides so the same value combination is not recorded twice.