I use hash maps to keep counts and remember values I've already seen. Instead of searching the input again, I look up the stored value by its key.
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.
For a frequency count, the key is the character and the value is its count. For a membership check, the value only needs to record that the key has appeared.
Examples in code
This function counts each character in a string:
function countChars(str) {
const counts = {};
for (let char of str) {
counts[char] = (counts[char] || 0) + 1;
}
return counts;
}
For an array of numbers, this version stops when a value appears twice:
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.
The lookup benefit costs memory: storing n distinct keys usually takes O(n) space. I use a hash map when that stored state removes repeated work.

Loading comments...