Note · 20 Jul 2026
Two Sum: the two lines everyone gets backwards
The hash map is the easy part. The order of the check and the store is what decides whether it is correct.
Two Sum is the first problem almost everyone solves, and the hash-map solution is repeated everywhere. What gets repeated far less often is why two specific lines have to be in a specific order — and what breaks when they are not.
The brute force, and why it is abandoned
Check every pair, return the two indices that sum to the target. Correct, and quadratic — for every element you rescan the rest of the array. On a large input that is the whole cost of the solution.
One pass instead of two loops
Walk the array once. At each number, work out what you still need to reach the target, and ask whether you have already seen it. If you have, you are done. If not, record the current number against its index and move on.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
mapping = {}
for i in range(len(nums)):
need = target-nums[i]
if need in mapping:
return [i, mapping[need]]
mapping[nums[i]]=iThe trap
Swap the last two lines — store first, then check — and the solution still passes plenty of tests. It breaks when the target is exactly twice a number in the array.
Take nums = [3, 4] with target = 6. Store the 3 at index 0. Now compute what you need: 6 − 3 = 3. Look it up, and the map already contains the 3 you just wrote. A single element matches itself, and you return [0, 0].
Checking before storing means the map only ever contains elements strictly to the left of the current one, so a match is always a genuinely different index. The correctness argument is the ordering, not the data structure.
Cost
- 01Time: O(n) — one pass, constant-time lookups
- 02Space: O(n) — the map holds at most every element
Also on video — watch the short ↗