Reputation: 69
I have the following function which takes in an array of numbers and a target value, if any 2 of the numbers in the array can be added to give the target value, the function returns true, if not it returns false. E.g if array = [5,4,2,3,1] and target = 9, the function should return true as 5+4=9. However if target = 10, the function should return false as no 2 numbers in the array can be added to give 10.
function Solution(array,target) {
for (var i = 0;i<array.length;i++) {
for (var j=0;j!=i && j<array.length;j++) {
if (array[i] + array[j] == target) {
return true
}
}
}
return false
}
The above function works as expected however I don't think this is a good way of doing it, can anybody show me a more efficient way using a map function?
Upvotes: 1
Views: 1312
Reputation: 50684
You can maintain a Set
to make this more efficient.
When you come across a new number in your array, subtract that number from the target sum. This will tell you the amount you need to add with the current number to get to the target sum. You can check to see if that number/amount is in the Set in O(1) using .has()
. If it is in the set, you can return true, otherwise, you can add the number to your set to be checked for further iterations of your array.
See example below:
function solution(array, target) {
const set = new Set();
for(const num of array) {
if(set.has(target-num))
return true;
set.add(num);
}
return false;
}
console.log(solution([5,4,2,3,1], 9));
Upvotes: 0
Reputation: 3302
Here is simple one line solution using array some method.
const Solution = (array, target) =>
array.some((x, i) => array.some((y, j) => i !== j && x + y === target));
console.log(Solution([5, 4, 2, 3, 1], 9));
console.log(Solution([5, 4, 3, 2, 1], 10));
console.log(Solution([5, 4, 3, 2, 1], 5));
Upvotes: 0
Reputation: 386560
You could take a hash table with the needed delta as key.
This approach needs only one iteration.
function solution(array, target) {
const seen = {};
for (const value of array) {
if (seen[value]) return true;
seen[target - value] = true;
}
return false;
}
console.log(solution([5, 4, 3, 2, 1], 9)); // true
console.log(solution([5, 4, 3, 2, 1], 10)); // false
Upvotes: 1