Hash maps appear throughout algorithm problems because they connect a key to a value and offer O(1) average lookup time. After I solved dozens of problems, I started to recognize recurring uses for hash maps.
Hash maps as key value storage
A hash map stores key value pairs. The key selects a location, so a lookup does not need to scan every stored value. The average cost is O(1), although collisions and the chosen implementation affect the details.
I use hash maps for membership checks, frequency counts, and associations between values. In each case, I choose a key and the value associated with it. Two examples make the pattern concrete.
Examples in code
When I needed to count characters in a string, a hash map held each character's count:
function countChars(str) {
const counts = {};
for (let char of str) {
counts[char] = (counts[char] || 0) + 1;
}
return counts;
}
For duplicate detection, I use a hash map to remember which values have appeared:
function hasDuplicate(nums) {
const seen = {};
for (let num of nums) {
if (seen[num]) return true;
seen[num] = true;
}
return false;
}
When another structure fits
I avoid hash maps when I need sorted keys or range queries. Their memory use can also be a constraint. A tree or another ordered structure can answer those queries more directly.
If a problem asks "have I seen this?" or "how many times?", I check whether a hash map can hold that state. The data structure usually uses O(n) space for n stored keys, so the lookup benefit has a clear memory cost.
Hash maps give fast average lookups, make frequency counting straightforward, and record relationships without a nested search. The right choice depends on whether the problem needs ordering, range queries, or lower memory use.

Loading comments...