Examples
Write twoSum so that the following cases hold.
- Input
twoSum([2,7,11,15], 9)Output[0,1] - Input
twoSum([3,2,4], 6)Output[1,2] - Input
twoSum([3,3], 6)Output[0,1]
1 more hidden test cases - 4 in total will be graded.
Answer
js
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 [];
}
twoSum([2, 7, 11, 15], 9); // [0, 1]
Nested loops are O(n²); a Map of already-seen values brings it to O(n). Return the indices in ascending order.
