WeCodeAcademy

Using a Dictionary: Two Sum

A classic question: given a list of numbers and a target, find two numbers that add up to it. The slow way tries every pair: O(n squared). The fast way remembers each number it has seen in a dictionary, and for each new number x asks "have I already seen target - x?". One pass, O(n).

This pattern, storing what you have seen so you can look it up instantly, solves a huge number of problems.

Examplepython
Open in editor »
Quick check

In two-sum, what do we look up in the dictionary for each number x?

Your turn: write the code

Write has_pair(nums, target) returning True if two different positions sum to target, using a set. Print has_pair for target 10 and then 20.

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.