- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- When a Hash Map Is the Wrong Choice
Hash Maps and Sets
When a Hash Map Is the Wrong Choice
Reaching for a Map by reflex is the second most common mistake after nested loops. It is fast at one thing - exact lookup - and unremarkable at everything else.
It has no useful order
A Map remembers insertion order, and nothing else. It cannot tell you the smallest key, the next key after this one, or everything between two values. Any of those means you want a sorted array or a tree.
The question a Map cannot answer
javascript
const ages = new Map([["ada", 36], ["grace", 45], ["alan", 41]])
// A Map cannot do this without walking everything:
// who is the youngest?
// who is between 35 and 42?
// Sorted, both are easy.
const sorted = [...ages.entries()].sort((a, b) => a[1] - b[1])
console.log(sorted[0]) // ["ada", 36] — youngest