Continue learning
Practice related DSA questions in the same topic.
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.
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 []Compare pair sum 10 with 10.
Compare pair sum 10 with 10.
Adjust two ends of a balance scale, moving only the side whose change improves the total.
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
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} ⇒ []
Identical values still require two distinct positions.
Why is sorted order essential to this elimination?