Two Sum
The single most-asked coding interview question. Given an array of integers nums and a target target, return the indices of the two numbers that add up to target. Exactly one solution exists, and you may not use the same element twice.
The naive answer is two nested loops (O(n²)). The answer they're looking for is one pass with a hash map (O(n)): for each number, check whether target - num is already in the map.
twoSum([2, 7, 11, 15], 9); // [0, 1] (2 + 7)
twoSum([3, 2, 4], 6); // [1, 2] (2 + 4)