Skip to content
dreamcode
dreamcode
Map
Hash map patterns
Lesson 61 of 77
+15 XP on finish
ALGORITHMSChapter 10 · Algorithms and Problem Solving

Remember what you have seen

Dictionaries and sets look things up in O(1) on average, so many problems become fast when you remember what you have already seen. Count things with a dict or Counter. Group things with a dict of lists (defaultdict(list) saves the setup). Find two numbers that add up to a target in a single pass by storing each number as you go.

Worked example

How it reads

  • Counter counts every item in one pass
  • defaultdict(list) creates an empty list the first time a key is used
  • two_sum asks "have I already seen the number I need?" instead of checking every pair
Cloud tip: Trading memory for speed is the most common algorithm trick there is: store what you learn, never recompute it.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Make first_repeat return the first letter that appears for a second time, reading left to right, or None. Use a set. It should print b then None.

Press Run to check your work.