File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
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)
You can’t perform that action at this time.
0 commit comments