This code works for the test cases having unique elements in the array but not if the same element is present like [3,2,3] so I want something like to add 3+3 === target(when the target is 6) and to get both of their indexes. Please explain me the logic and upto this rate my approach which I used here.
function twoSum(nums, target) {
return nums.reduce((acc, ele, index) => {
if (ele + nums.at(index + 1) === target) {
acc.push(index, index + 1)
}
return acc
}, [])
}
const nums = [2, 7, 11, 15]
const target = 9
console.log(twoSum(nums, target))
const nums1 = [3,2,3]
const target1 = 6
console.log(twoSum(nums1, target1))
2
Answers
Iterate all possible combinations of 2 elements and collect their indices:
An
Array::reduce()
version:Benchmark with a small set:
Benchmark with a big set:
We can use a map and iterate over the array, storing each element’s value and index. We then check for each element if its complement is already in the map. If found, we iterate over the array of indices for the complement, and for each index, add a pair of indices to the result to handle reuse of a digit.
Time complexity still: O(n)
Due to the possible multiple results, single results are also nested. We can flatten them if you do not like it.
This one looks more elegant but is O(n^2)