'Why is this solution correct? From what I see, it doesn't meet an edge case
In the case with the below, according to the algorithm, wouldn't 3 : 0 be considered as an output? Since the difference is 3 and its index will be 0 hence not giving undefined. Hence what I'm thinking is the difference can't be half of the target for this algo to work. What am I missing here?
Example 2:
Input: nums = [3,2,4], target = 6 Output: [1,2]
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
var twoSum = function(nums, target) {
let secondNumberMap = new Map();
nums.map((item,index)=>{
if(target>item){
// Saving the second number as key vs first number index as the value
secondNumberMap.set(target-item,index);
}
})
for(let i=0;i<nums.length;i++){
const firstNumberIndex = secondNumberMap.get(nums[i]);
if(firstNumberIndex!==undefined){
return [firstNumberIndex,i];
}
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
