forked from FS-Moringa/phase-1-algorithms-has-target-sum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
49 lines (38 loc) · 1.32 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function hasTargetSum(array, target) {
// Write your algorithm here
const seenNumbers = {};
for (const number of array) {
const complement = target - number;
if (complement in seenNumbers) return true;
seenNumbers[number] = true;
}
return false;
}
/*
Write the Big O time complexity of your function here
Runtime: O(n^2)
Space: O(n)
*/
/*
Add your pseudocode here
*/
/*
Add written explanation of your solution here
first create an empty object to store the numbers that have already been looped through to avoid using 2 for loops
then create a for loop that iterates through the array then minus that value from the target then introdude in an
if statement to compare if the value we get from after subtracting from the target compares to the object of numbers we had
looped through in order to avoid using a second for loop
*/
// You can run `node index.js` to view these console logs
if (require.main === module) {
// add your own custom tests in here
console.log("Expecting: true");
console.log("=>", hasTargetSum([3, 8, 12, 4, 11, 7], 10));
console.log("");
console.log("Expecting: true");
console.log("=>", hasTargetSum([22, 19, 4, 6, 30], 25));
console.log("");
console.log("Expecting: false");
console.log("=>", hasTargetSum([1, 2, 5], 4));
}
module.exports = hasTargetSum;