Hash MapAI-assisted round
Find two numbers that add to a target
Given a list of numbers and a target, return the indexes of the two numbers that add up to the target. Each input has exactly one answer, and you can't use the same element twice.
AIThe assistant proposed this solution
“I'll use a hash map to get O(n) time. I store each number's index as I go, then check whether the complement (target − current number) is already in the map. If it is, I've found the pair. Storing first keeps the loop clean.”
1function twoSum(nums, target) {
2 const seen = {};
3 for (let i = 0; i < nums.length; i++) {
4 seen[nums[i]] = i;
5 const complement = target - nums[i];
6 if (seen[complement] !== undefined) {
7 return [seen[complement], i];
8 }
9 }
10 return [];
11}
Before you accept this, make the call. What's your verdict?