Back to Coding Prep
Coding
Hash maps
Trade space for O(1) lookups; complement / seen-set tricks.
Coding pattern
Overview
Hash maps trade memory for speed, turning repeated lookups from O(n) scans into O(1) queries. The skill is spotting when a problem is secretly asking 'have I seen this before?' and modeling it with the right key so a second nested loop disappears.
How it works
Coding patternClientDataServiceEdge
Step by step, with examples
- 1
Keys/values
- Identify what you need to look up in O(1).
- 2
Hash table
- Insert entries as you scan; test membership cheaply.
- 3
Complement
- Query the map instead of nesting a second loop.
- 4
Answer
- Emit a pair, count, or grouping.
- Example: Two Sum, group anagrams
When to reach for it
- 'Have I seen this?' questions
- Counting
- Grouping by key
Example problem
Two Sum — find indices that add to a target.
Approach
- Store value → index as you scan
- Look up target − num before inserting
Solution
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);
}
}Complexity
Time O(n), Space O(n).
Common pitfalls
- Using the same element twice
- Hash collisions in worst case
Where this content comes from
For full transparency, this content is curated and verified from these sources:
Curated company-tagged problem banksRecurring interview pattern librariesOppZen-authored drills & solutions