Skip to content
dreamcode
dreamcode
Map
Hash map patterns
Lesson 42 of 48
+15 XP on finish
JS ALGORITHMSChapter 8 · JS Algorithms

Remember What You Have Seen

Maps, Sets and plain objects look things up in O(1) on average, so many problems become fast when you remember what you have already seen. Count with a Map. Group into an object of arrays. Find two numbers that add up to a target in one pass by storing each number as you go, instead of checking every pair.

Worked example

How it reads

  • The Map counts every word in a single pass
  • ||= creates the array the first time a length appears
  • twoSum asks "have I seen the number I need?" instead of trying every pair
Cloud tip: Storing what you learn so you never recompute it is the most useful algorithm trick there is.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Make firstRepeat return the first letter that appears a second time, reading left to right, or null. Use a Set. It should print b then null.

Press Run to check your work.