Look up the complement before inserting the current value. One pass, O(n).
Walk the array once. At each element ask the map “is `target − x` already here?”. If yes, the stored index plus the current one is the answer. If not, record x → i and keep going.
Because we check before we insert, the map only ever contains elements strictly to the left of the current index, which is exactly the set of legal partners.
Algorithm
- Create an empty map
seenfrom value → index. - For each
(i, x)computeneed = target − x. - If
needis inseen, return[seen[need], i]. - Otherwise store
seen[x] = iand continue.
- Time
- O(n)
- Space
- O(n)
Each element is hashed at most twice (one lookup, one insert).
class Solution: def twoSum(self, nums: list[int], target: int) -> list[int]: seen: dict[int, int] = {} # value -> index for i, x in enumerate(nums): need = target - x if need in seen: return [seen[need], i] seen[x] = i return [] # unreachable: exactly one solution is guaranteed