Half of all "medium" interview problems have the same secret: trade memory for speed with a hashmap. O(1) insert, O(1) lookup.
Pattern 1 — frequency counter
const freq = {};
for (const ch of "engineering") {
freq[ch] = (freq[ch] || 0) + 1;
}
// {e:3, n:3, g:2, i:2, r:1}
// → anagrams, first-unique-char, majority element: all this patternPattern 2 — "have I seen this?"
// Two Sum in O(n) — THE interview classic
function twoSum(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
if (seen.has(target - nums[i])) return [seen.get(target - nums[i]), i];
seen.set(nums[i], i);
}
}Map vs plain object
Map: any key type, remembers insertion order, has.size- Object: string keys only, but shorter syntax — fine for counters
Set: Map with only keys — dedupe and membership checks
Five problems on our judge fall to these two patterns — go collect them.
← All Articles