Loading TechCookies content…
The most common interview pattern is: "I need to look up a value I saw earlier in O(1)." A hash map is the answer.
Without a hash map, looking up "have I seen X before?" requires scanning all previous elements: O(n) per lookup → O(n²) total. With a hash map: O(1) average per lookup → O(n) total.
// O(n²) brute force
function twoSum(nums: number[], target: number): number[] {
for (let i = 0; i < nums.length; i++)
for (let j = i+1; j < nums.length; j++)
if (nums[i] + nums[j] === target) return [i, j];
return [];
}
// O(n) with hash map
function twoSum(nums: number[], target: number): number[] {
const seen = new Map<number, number>(); // value → index
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (seen.has(complement)) return [seen.get(complement)!, i];
seen.set(nums[i], i);
}
return [];
}
Trace the hash version on nums = [3, 7, 1], target = 10:
| i | nums[i] | complement | in seen? | action |
|---|---|---|---|---|
| 0 | 3 | 7 | no | store 3 → 0 |
| 1 | 7 | 3 | yes (index 0) | return [0, 1] ✓ |
One pass, each step O(1). Hash maps trade space for time: you pay O(n) space to buy O(n) time instead of O(n²) — the same conscious swap from the Big-O concept.