STEP 3 · ARRAYS · HASHING · EASY
Two Sum
WHAT IT SAYS
Return indices of two numbers that add up to a target.
WHAT IT'S REALLY ASKING
"As you walk the array, have you already seen the number that completes me?"
THE INSIGHT LADDER — FROM BRUTE FORCE TO OPTIMAL
Brute force: try every pair
O(n²) time · O(1) spaceTwo nested loops — for each element, scan the rest of the array hoping to find its partner.
WHERE THE WORK IS WASTED — For every element you re-walk territory you've already covered.
!
KEY OBSERVATION — THE UNLOCKlink
You are not searching. You are remembering.
The partner of nums[i] is fully determined: target − nums[i]. A question whose answer you can compute is a lookup, not a search. Lookups want a hash map.
One pass with a ledger
O(n) time · O(n) spaceBefore recording each number, ask the map for target − x. The map looks back so you never have to.
WHAT YOU TRADED — You bought O(1) recall with O(n) memory — space for the right to never re-scan.
WATCH THE IDEA RUN
5
02
111
23
39
48
5need 7
found no
Need 7. Never seen it — record 5, move on.
step 1 / 5
THE PATTERN — SO YOU RECOGNIZE IT NEXT TIME
Search → Lookup
YOU'LL SEE IT AGAIN WHEN
- You're repeatedly scanning for a value
- That value is computable in O(1) from the current element
SAME BLUEPRINT, DIFFERENT PROBLEM
Subarray Sum Equals KLongest Consecutive Sequence
The bar isn't "solved it once." It's "could rebuild it from the observation."