Skip to content

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]
#Stepinums[i]needseen
17 not seen, store 2027{}
22 is in seen at 0, return172{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);