1
1
var threeSum = function ( nums ) {
2
+ // Create array a to store output array
2
3
let a = [ ]
4
+ // Create variable j and k for indexing nums[j] and nums[k]
5
+ // Create val1 and val2 for storing value of nums[j] and nums[k] respectively
3
6
let [ j , k , val1 , val2 ] = [ 0 , 0 , 0 , 0 ]
7
+ // sort the input array ascendingly
4
8
nums . sort ( function ( a , b ) { return a - b } )
5
- for ( let i = 0 ; i < nums . length - 2 ; i ++ ) {
9
+ // run loop over nums from (0,nums.length-2)
10
+ // we need i , j , k so last usable index of will be nums.length-2
11
+ // storing length helps a little bit for optimization
12
+ len = nums . length
13
+ for ( let i = 0 ; i < len - 2 ; i ++ ) {
14
+ // nums[i] must be negative or 0 to get nums[i] + nums[j] + nums[k] == 0
6
15
if ( nums [ i ] > 0 ) { continue }
16
+ // we will cover all possible triplet for nums[i] so we dont need to rerun for same value
7
17
if ( nums [ i ] == nums [ i - 1 ] ) { continue }
18
+ // j will be the start pointer and k will be end pointer for our window
8
19
j = 1 + i
9
- k = nums . length - 1
20
+ k = len - 1
21
+ // we will run this until the whole window is convered
10
22
while ( j < k ) {
11
23
if ( nums [ i ] + nums [ j ] + nums [ k ] == 0 ) {
24
+ // if this condition is met we add it to answer array
12
25
a . push ( [ nums [ i ] , nums [ j ] , nums [ k ] ] )
26
+ // we store value of nums[j] in val1
13
27
val1 = nums [ j ] ;
28
+ // we skip all index with same value as nums[j] this will help up shorten the window
14
29
while ( j < k && nums [ j ] == val1 ) j ++ ;
15
30
val2 = nums [ k ] ;
31
+ // we skip all index with same value as nums[k] this will help up shorten the window
16
32
while ( j < k && nums [ k ] == val2 ) k -- ;
17
- } else if ( nums [ i ] + nums [ j ] + nums [ k ] < 0 ) j ++ ;
33
+ // if total is < 0 we try to get a greater value for nums[j] (array is sorted ascending)
34
+ } else if ( nums [ i ] + nums [ j ] + nums [ k ] < 0 ) j ++ ;
35
+ // if total is > 0 we try to get a smaller value for nums[k] (array is sorted ascending)
18
36
else if ( nums [ i ] + nums [ j ] + nums [ k ] > 0 ) k -- ;
37
+ // thus when this loop is done we will have all possible j and k for given nums[i]
19
38
}
20
39
}
40
+ // return the output array
21
41
return a
22
- } ;
42
+ } ;
0 commit comments