BeginnerCoder

Lesson 10 — Two-sum with hashmap

Two-sum: trade memory for speed

Task: find two numbers in a list that add up to a target. Checking every pair is O(n²). Faster: walk once and keep a dict (a hash map — a lookup table with near-instant access) of numbers seen so far → their index. For each x, the partner you need is target − x. If it is already in the dict, you are done.

seen = {2: 0}
9 - 7 in seen   # True: 2 was at index 0

Why it matters: "remember what you have seen in a dict" turns many slow double loops into one fast loop — a favourite interview pattern.

Want it another way?
Task

Fill in the check and the store. Expected: [0, 1], then [1, 2].

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.