Skip to content

Commit 6feab8f

Browse files
committed
feat: Solves Three Number Sum
1 parent dd9d486 commit 6feab8f

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

arrays-strings/three-number-sum.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* AlgoExpert
3+
*
4+
* Write a function that takes in a non-empty array of distinct integers and an
5+
* integer representing a target sum. The function should find all triplets in
6+
* the array that sum up to the target sum and return a two-dimensional array of
7+
* all these triplets. The numbers in each triplet should be ordered in ascending
8+
* order, and the triplets themselves should be ordered in ascending order with
9+
* respect to the numbers they hold.
10+
*
11+
* If no three numbers sum up to the target sum, the function should return an
12+
* empty array.
13+
*/
14+
15+
/**
16+
* @param {number[]} array
17+
* @param {number} targetSum
18+
* @returns {array[][]}
19+
*/
20+
function threeNumberSum(array, targetSum) {
21+
// O(n^2) time | O(n) space
22+
23+
// Edge case
24+
if (array.length < 3) {
25+
return [];
26+
}
27+
28+
const triplets = [];
29+
array.sort((a, b) => a - b);
30+
31+
const arrayLength = array.length;
32+
let i = 0;
33+
let l, r;
34+
while (i < arrayLength - 2) {
35+
const currentElement = array[i];
36+
l = i + 1;
37+
r = arrayLength - 1;
38+
39+
while (l < r) {
40+
const leftElement = array[l];
41+
const rightElement = array[r];
42+
const total = currentElement + leftElement + rightElement;
43+
if (total === targetSum) {
44+
triplets.push([currentElement, leftElement, rightElement]);
45+
l++;
46+
r--;
47+
} else if (total > targetSum) {
48+
r--;
49+
} else {
50+
l++;
51+
}
52+
}
53+
54+
i++;
55+
}
56+
57+
return triplets;
58+
}

0 commit comments

Comments
 (0)