Two Sum in a Sorted Array
In sorted input return indices of a pair summing to the target, or an empty array. Resolve ties with the earliest left index and latest matching right index.
In sorted input return indices of a pair summing to the target, or an empty array. Resolve ties with the earliest left index and latest matching right index.
Input and constraints
- Values must be in nondecreasing order.
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): left = 0 right = (len(values) - 1) while (left < right): total = (values[left] + values[right]) if (total == target): return [left, right] if (total < target): left = (left + 1) else: right = (right - 1) return []Visualizer
Step 1 of 2Inspect the current state
Compare pair sum 10 with 10.
Variable watch
Step explanation
Compare pair sum 10 with 10.
Worked explanation
Adjust two ends of a balance scale, moving only the side whose change improves the total.
Guided solution
If the sum is too small, the left item cannot work with any remaining partner. A too-large sum rules out the right item.
O(n) time · O(1) auxiliary space
Examples
Worked example · {"values":[1,3,4,7,9],"target":10} ⇒ [0,4]
Edge case 1 · {"values":[3],"target":6} ⇒ []
Edge case 2 · {"values":[],"target":2} ⇒ []
Progressive hints
Hint 1
Adjust two ends of a balance scale, moving only the side whose change improves the total.Hint 2
If the sum is too small, the left item cannot work with any remaining partner. A too-large sum rules out the right item.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Identical values still require two distinct positions.
Interview follow-up
Why is sorted order essential to this elimination?