DSA patterns
LeetCode questions by pattern, a cheat sheet, a pattern drill and step-by-step dry runs.
1Two Sum
- Input
- nums = [2,7,11,15], target = 9
- Output
- [0, 1]
| # | Step | i | nums[i] | need | seen |
|---|---|---|---|---|---|
| 1 | 7 not seen, store 2 | 0 | 2 | 7 | {} |
| 2 | 2 is in seen at 0, return | 1 | 7 | 2 | {2: 0} |
Code that was traced
function twoSum(nums, target) {
const seen = new Map();
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 twoSum([2, 7, 11, 15], 9);