Codingeasyarrayshash-mapleetcode-1
Two-sum: find two numbers in an array that add to a target
Framework
- Clarify: can elements repeat? are there always two answers? sorted input?
- Brute force: O(n²) double loop — mention it, then optimize
- Optimal: hash map of {value → index}; for each x, check if (target - x) is in the map
- Time: O(n). Space: O(n).
- Walk through one example end-to-end out loud
Sample answer
```ts
function twoSum(nums: number[], target: number): [number, number] | null {
const seen = new Map<number, number>(); // value → index
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen.has(need)) return [seen.get(need)!, i];
seen.set(nums[i], i);
}
return null;
}
```
Talk through it: "I keep a map of values I've seen and their indices. For
each new number, I check if its complement is already in the map. Single
pass, constant-time lookup, linear time overall."Common pitfalls
- Coding silently — interviewer wants to hear you think
- Forgetting to handle 'no solution' case
- Not stating Big-O until prompted