javascript example
Two Sum in JavaScript
Find two numbers that add up to a target. A common interview warm-up you can run online.
A Map from value to index lets you check the complement in one pass. That is the usual O(n) approach.
Log the pair of indices. Then change the array or target and Run again.
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 null;
}
console.log(twoSum([2, 7, 11, 15], 9));