Given an array of numbers and a target, return the indices of the two numbers that add up to the target.
Brute force is O(n^2). The optimal solution is a single pass with a hash map: for each number, check whether target - number was already seen; if so, return the stored index and the current index.
function twoSum(nums, target) {
const seen = new Map(); // 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 [];
}The complement-in-a-hashmap pattern is the most reused technique in coding interviews and appears in pair-matching, deduplication, and cache-hit logic.
A candidate inserts nums[i] into the map BEFORE checking for the complement. What bug does that cause for target = 6, nums = [3, ...]?