1. Value → index map
A Map remembers each value's index for O(1) lookup.
const seen = new Map()Typorithm · easy
Step 1 of 8 · intro card
Arrays & Hashing
Store each value's index in a Map; for each number, check if its complement was already seen.
The brute-force pair check is O(n^2); hashing trades a little memory for O(n) time.
For each number, its complement is target minus itself.
If that complement is already in the Map, the answer is its stored index and the current one.
Map stores value → index.
Check the complement first, then store.
One pass, O(n) time.
function twoSum(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i += 1) {
const need = target - nums[i];
if (seen.has(need)) {
return [seen.get(need), i];
}
seen.set(nums[i], i);
}
return [];
}Connect each part of the code to the concept before you type.
A Map remembers each value's index for O(1) lookup.
const seen = new Map()The partner value that would complete the target sum.
const need = target - nums[i]If the complement was stored earlier, the pair is found.
if (seen.has(need))Store the current value and index for future complements.
seen.set(nums[i], i)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.