Continue learning
Practice related DSA questions in the same topic.
Find two distinct positions whose values add to the target. Return the pair with the smallest second index, then smallest first index. Return an empty array if no pair exists.
Find two distinct positions whose values add to the target. Return the pair with the smallest second index, then smallest first index. Return an empty array if no pair exists.
def solve(values, target): seen = [0] * (2001) i = 0 while (i < len(values)): need = (target - values[i]) if ((need >= -1000) and (need <= 1000)): if (seen[(need + 1000)] > 0): return [(seen[(need + 1000)] - 1), i] if (seen[(values[i] + 1000)] == 0): seen[(values[i] + 1000)] = (i + 1) i = (i + 1) return []Look for the earlier complement 5.
Look for the earlier complement 5.
At a ticket booth, remember who can provide the change you will need later.
As each value arrives, look up the earliest position of its complement. Store indices plus one so zero marks an unseen value.
O(n + U), U = 2001 time · O(U) auxiliary space
For each second index, inspect earlier entries from left to right.
O(n²) time · O(1) auxiliary space
Worked example · {"values":[4,1,7,2],"target":9} ⇒ [2,3]
Edge case 1 · {"values":[3,3],"target":6} ⇒ [0,1]
Edge case 2 · {"values":[],"target":2} ⇒ []
Edge case 3 · {"values":[1,4,6,9],"target":10} ⇒ [1,2]
Looking up a complement after recording the current value can reuse the same item.
How would you return all matching index pairs?