Skip to content

Commit a69b246

Browse files
committed
Add 3sum solution
1 parent 8ed6b2b commit a69b246

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

3sum/Jeehay28.js

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[][]}
4+
*/
5+
6+
7+
// Time Complexity: O(n^2)
8+
// Space Complexity: O(n^2)
9+
10+
var threeSum = function (nums) {
11+
12+
const sorted = [...nums].sort((a, b) => a - b);
13+
14+
let result = [];
15+
16+
// Loop through the array and pick each number as the first number for the triplet
17+
for (let i = 0; i < sorted.length - 2; i++) {
18+
19+
// skip duplicate values for sorted[middle]
20+
if(i > 0 && sorted[i - 1] === sorted[i]) {
21+
continue;
22+
}
23+
24+
let left = i + 1; // Left pointer starts right after the current middle
25+
let right = sorted.length - 1; // Right pointer starts at the last element
26+
27+
while (left < right) {
28+
const sum = sorted[i] + sorted[left] + sorted[right];
29+
30+
if (sum === 0) {
31+
result.push([sorted[left], sorted[i], sorted[right]]);
32+
33+
// skip duplicates for sorted[left] and sorted[right]
34+
while(left < right && sorted[left] === sorted[left + 1]){
35+
left += 1; // Move left pointer to the right to skip duplicate values
36+
}
37+
38+
while(left < right && sorted[right] === sorted[right - 1]) {
39+
right -= 1; // Move right pointer to the left to skip duplicate values
40+
}
41+
42+
left += 1;
43+
right -= 1;
44+
45+
} else if (sum > 0) {
46+
right -= 1;
47+
48+
} else {
49+
left += 1
50+
}
51+
}
52+
}
53+
54+
return result;
55+
56+
};
57+
58+
59+
// var threeSum = function (nums) {
60+
61+
// i != j, i != k, and j != k can be interpreted as i < j < k
62+
63+
// three nested loops
64+
// time complexity of O(n³)
65+
// Time Limit Exceeded
66+
67+
// let result = [];
68+
69+
// for (let i = 0; i < nums.length - 2; i++) {
70+
// for (let j = i + 1; j < nums.length - 1; j++) {
71+
// for (let k = j + 1; k < nums.length; k++) {
72+
// if (nums[i] + nums[j] + nums[k] === 0) {
73+
// const str = [nums[i], nums[j], nums[k]].sort((a, b) => a - b).join(",")
74+
// result.push(str)
75+
// }
76+
// }
77+
// }
78+
79+
// }
80+
81+
// result = [... new Set(result)].map(str => str.split(",").map(str => +str))
82+
83+
// return result;
84+
85+
// }
86+

0 commit comments

Comments
 (0)