Code + the reasoning behind every line
See the solution on the left and a plain-English explanation for every line on the right.
- 1def two_sum(nums, target):
- 2 seen = {}
- 3 for i, n in enumerate(nums):
- 4 if target - n in seen:
- 5 return [seen[target - n], i]
- 6 seen[n] = i
- Define the function signature.
- A hash map gives O(1) lookups.
- Walk the list once, tracking the index.
- Check whether the complement was seen.
- Found it — return both indices.
- Remember this number for later.