A hash map stores key-value pairs and gives fast access by key.
In JavaScript, Map is a good general-purpose hash map. Plain objects can also work, but Map avoids many edge cases around inherited keys.
Basic usage
const counts = new Map();
for (const value of values) {
counts.set(value, (counts.get(value) ?? 0) + 1);
}
This code counts how many times each value appears.
Why hash maps matter
Many slow nested-loop solutions become faster when you store information in a hash map.
Example: two sum.
function twoSum(values, target) {
const seen = new Map();
for (let i = 0; i < values.length; i++) {
const needed = target - values[i];
if (seen.has(needed)) {
return [seen.get(needed), i];
}
seen.set(values[i], i);
}
return [];
}
Common uses
- frequency counting
- checking if a value exists
- grouping by category
- caching computed answers
- mapping value to index
Complexity
Hash map operations are usually O(1) on average, but can degrade if many keys collide. For interview and practice problems, average O(1) is usually assumed.
Practice problems
- Two sum.
- First non-repeating character.
- Group anagrams.
- Contains duplicate.
- Count pairs with a given difference.
Practice links
Interactive walkthrough
Hash Map Visualizer
Track values as keys for fast lookup and counting. Step 1 key
Step 2 value
Step 3 seen
Step 4 count