|
1 |
| -// the best case using a data structure - SET |
2 |
| -function findTwoNumsAddingToN(arr, sum) { |
3 |
| - const nums = []; |
| 1 | +// the best case [O(n)] using SET data structure |
| 2 | +function findTwoNumsAddingToN(arr, number) { |
| 3 | + const pair = []; |
4 | 4 | const store = new Set();
|
5 | 5 |
|
6 |
| - for (let i = 0; i < arr.length; i++) { |
7 |
| - // check if the set contains one of the pir that sum upto given sum |
8 |
| - if (store.has(sum - arr[i])) { |
9 |
| - nums.push(sum - arr[i]); |
10 |
| - nums.push(arr[i]); |
| 6 | + for (let i = 0; i < arr.length; i += 1) { |
| 7 | + // check if the set contains one of the pair that sum upto given number |
| 8 | + if (store.has(number - arr[i])) { |
| 9 | + pair.push(number - arr[i]); |
| 10 | + pair.push(arr[i]); |
11 | 11 | break;
|
12 | 12 | }
|
13 | 13 | // push the element in the set
|
14 | 14 | store.add(arr[i]);
|
15 | 15 | }
|
16 |
| - return nums.length ? nums : false; |
| 16 | + return pair.length ? pair : false; |
17 | 17 | }
|
18 | 18 |
|
19 | 19 | // the Brute force approach
|
20 |
| -function findTwoNumsAddingToN2(arr, sum) { |
21 |
| - const nums = []; |
22 |
| - for (let i = 0; i < arr.length; i++) { |
23 |
| - for (let j = i + 1; j < arr.length; j++) { |
24 |
| - if (arr[i] + arr[j] === sum) { |
25 |
| - nums.push(arr[i], arr[j]); |
| 20 | +function findTwoNumsAddingToN2(arr, number) { |
| 21 | + const pair = []; |
| 22 | + for (let i = 0; i < arr.length; i += 1) { |
| 23 | + for (let j = i + 1; j < arr.length; j += 1) { |
| 24 | + if (arr[i] + arr[j] === number) { |
| 25 | + pair.push(arr[i], arr[j]); |
26 | 26 | break;
|
27 | 27 | }
|
28 | 28 | }
|
29 | 29 | }
|
30 | 30 |
|
31 |
| - return nums.length ? nums : false; |
| 31 | + return pair.length ? pair : null; |
32 | 32 | }
|
0 commit comments