March 24
Hash Map
What a hash map is, how JavaScript Map works, and when to use it instead of scanning an array again.
What it is
A hash map is a data structure that stores key-value pairs.
The advantage is that you can look up a value by key without scanning everything.
In JavaScript
Map is the direct implementation:
const seen = new Map<number, number>()
seen.set(2, 0)
seen.has(2)
seen.get(2)
Plain objects can work for simpler cases, but Map is usually clearer when keys vary in type or you care about insertion order.
When to use it
Use Map when you need to:
- remember whether something already appeared
- keep a value associated with another value while iterating
- do fast lookups by key at any point in the algorithm
Why it shows up so often
A lot of optimization problems are really the same pattern:
you are iterating once and need quick memory of what you saw before.
That is how many O(n²) solutions become O(n).
Mapis not the point. Fast memory during the pass is the point.
Share this page
Copy the link manually from the field below.