Hashing for Lookup
Hashing for lookup means putting values in a Map or Set so later membership and retrieval are average O(1) instead of an O(n) scan.
Detailed Explanation
The slow version of many interview problems is "for each item, scan the rest". The fast version is "put what you have seen in a hash table, then ask whether the complement is there". Two-sum, anagram grouping, counting pairs, and "first unique character" are this move.
In JavaScript the hash tables you actually use are Object (string keys), Map (any key), and Set (any value). You do not write a hash function for ordinary keys. The engine hashes strings, numbers, and object identities for you.
The algorithm pattern:
- Choose the key that makes the question O(1). For two-sum it is
target - x. For anagrams it is a sorted string or a count signature. For "visited" it is the node itself. - Decide
SetvsMap.Setwhen you only askhas.Mapwhen you need a payload (index, count, list of group members). - Walk once. Update the table as you go if the problem is "seen so far", or fill the table first if the problem is "exists anywhere".
Average O(1) is not worst-case O(1). Pathological string keys can collide; you will not hit this with normal ids. What you will hit is using an object as a key when you meant its id: map.set({ id }, v) cannot be retrieved with a new { id }.
Counting with a map is map.set(k, (map.get(k) ?? 0) + 1). Grouping is map.set(k, (map.get(k) ?? []).concat(item)) or a push onto a stored array.
What it costs you: O(n) extra memory, and a wrong key. Hashing does not order results; if you need the first occurrence, store the first index and do not overwrite it. Objects as maps inherit prototype-key bugs; prefer Map/Set.
Reach for a hash table when you look up by identity or by a computed signature. Reach for sorting plus two pointers when you need pairs in a sorted sense and extra memory is tight. Reach for an array of counts when the alphabet is tiny (new Array(26) for lowercase letters).
Code Examples
function twoSum(nums, target) {
const seen = new Map(); // value -> index
for (let i = 0; i < nums.length; i += 1) {
const need = target - nums[i];
if (seen.has(need)) return [seen.get(need), i];
seen.set(nums[i], i);
}
return null;
}
console.log(twoSum([2, 7, 11, 15], 9)); // => [ 0, 1 ]function groupAnagrams(words) {
const groups = new Map();
for (const word of words) {
const key = [...word].sort().join("");
const list = groups.get(key) ?? [];
list.push(word);
groups.set(key, list);
}
return [...groups.values()];
}
console.log(groupAnagrams(["eat", "tea", "tan", "ate"]));
// => [ [ 'eat', 'tea', 'ate' ], [ 'tan' ] ]function firstUnique(s) {
const counts = new Map();
for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (let i = 0; i < s.length; i += 1) {
if (counts.get(s[i]) === 1) return i;
}
return -1;
}
console.log(firstUnique("leetcode")); // => 0Common Gotchas
Object keys are references
hash by `user.id`, not by `user`, unless you will pass the same object instance.
A plain object as a frequency table can clash with inherited names
use `Map` or `Object.create(null)`.
`sort().join` as an anagram key is O(k log k) per word
for a 26-letter alphabet, a count tuple is O(k).
Fill-first vs seen-so-far
two-sum usually updates after the check so you do not pair an element with itself.