Boss lesson · Unit 04
Two Sum
From every pair to one pass with a map
What you practise
- Brute force O(n²), then one pass with a complement map
- Why you check before you store
Try a question from this lesson
Pick one
Two Sum: find two different positions whose numbers add up to a target. For [2, 7, 11, 15] and target 9, which positions?
Correct answer
0 and 1
Why
2 + 7 = 9, at indexes 0 and 1. By eye that was easy. The question for this lesson is how many steps a program needs when the list has a million numbers.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Ask for the complement
Standing at a number x, you know exactly which partner you need: target - x, its complement.
So keep a map from every number seen so far to its index. One O(1) lookup tells you whether the partner has already gone by. One pass over the list: O(n).
11 more exercises in the app
- 2× fill the blanks
- 4× multiple choice
- 2× type the answer
- 1× order the lines
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.