Skip to content

Commit 6686b74

Browse files
committed
Added 3sum solution
1 parent 84f9275 commit 6686b74

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

3sum/nhistory.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
var threeSum = function (nums) {
2+
// Sort nums array
3+
const sortedNums = nums.sort((a, b) => a - b);
4+
let result = [];
5+
6+
// Start iteration to pick first element for 3sum
7+
for (let i = 0; i < sortedNums.length; i++) {
8+
// Check if the first element is already greater than 0, no valid triplets possible after this point
9+
if (sortedNums[i] > 0) {
10+
break;
11+
}
12+
13+
// Skip duplicates of the first element to avoid redundant triplets
14+
if (i > 0 && sortedNums[i] === sortedNums[i - 1]) {
15+
continue;
16+
}
17+
18+
// Iterate to find sum of two pointer and nums[i]
19+
let left = i + 1;
20+
let right = sortedNums.length - 1;
21+
22+
while (left < right) {
23+
let sum = sortedNums[i] + sortedNums[left] + sortedNums[right];
24+
25+
if (sum === 0) {
26+
result.push([sortedNums[i], sortedNums[left], sortedNums[right]]);
27+
// Skip duplicates of left and right pointers to avoid redundant triplets
28+
while (sortedNums[left] === sortedNums[left + 1]) left++;
29+
while (sortedNums[right] === sortedNums[right - 1]) right--;
30+
left++;
31+
right--;
32+
} else if (sum < 0) {
33+
left++;
34+
} else if (sum > 0) {
35+
right--;
36+
}
37+
}
38+
}
39+
return result;
40+
};
41+
42+
// TC: O(n^2)
43+
// SC: O(n)

0 commit comments

Comments
 (0)