Two Sum is problem #1 on LeetCode and one of the most common interview questions ever. Most people solve it the slow way. Let's solve it the slow way, then the fast way, and learn the hash map pattern behind dozens of other questions.
Video version:
The problem
Given a list of numbers and a target, return the indexes of the two numbers that add up to the target.
two_sum([2, 7, 11, 15], 9) # → [0, 1] because 2 + 7 = 9 two_sum([3, 2, 4], 6) # → [1, 2] because 2 + 4 = 6 Solution 1: check every pair
def two_sum_brute(nums, target): for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j] It works, and it's fine to mention first in an interview. But for every number, it scans the rest of the list. That's O(n²): 10,000 numbers means about 50 million pairs.
Solution 2: remember what you've seen
Flip the question. For each number, don't search for its partner. Ask: have I already seen the number I need? The number you need is target - n.
def two_sum(nums, target): seen = {} # value → index for i, n in enumerate(nums): if target - n in seen: # O(1) lookup return [seen[target - n], i] seen[n] = i Dictionary lookups are O(1) on average, so this is a single pass: O(n).
Note the order: we check before storing n. That way a number can't pair with itself. For example, [3, 2, 4] with target 6 doesn't wrongly return [0, 0].
Step by step
[2, 7, 11, 15], target 9:
i=0 n=2 need 7 seen={} → store 2 i=1 n=7 need 2 seen={2: 0} → found! ✅ return [0, 1] It never looks back through the list.
Measured: 10,000 numbers (worst case)
With the answer pair at the very end of the list:
brute force: 0.862 s hash map: 0.48 ms ≈ 1,800× faster ✅ And the gap keeps growing with the input: in theory, doubling the list makes the brute force about 4× slower (n²), but the hash map only about 2× slower (n).
How to explain it in the interview
- Start with brute force, and state its complexity: O(n²) time, O(1) space.
- Spot the repeated work: you keep searching for the partner.
- Trade memory for speed: a dict of the values you've seen.
- Result: O(n) time, O(n) space.
- Mention the pattern. The same idea solves duplicate detection, anagram grouping and subarray-sum problems.
Interviewers care as much about steps 1–3 (your reasoning) as about the final code.
Next in the interview series: memoization, where one line makes a function a million times faster.
I post one tested coding tip every day on YouTube at Refactorly. The 30-second version of this one is here.

