- Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy paththree_sum.js
More file actions
Latest commit
37 lines (36 loc) · 1.08 KB
/
Copy paththree_sum.js
File metadata and controls
37 lines (36 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
varthreeSum=function(nums){
// Sort the array
nums.sort((a,b)=>a-b);
// Length of the array
constn=nums.length;
// Resultant list
consttriplets=[];
// Loop for each element of the array
for(leti=0;i<n;i++){
// Skip the duplicates
if(i>0&&nums[i]===nums[i-1]){
continue;
}
// Left and right pointers
letj=i+1;
letk=n-1;
// Loop for all the remaining pairs
while(j<k){
if(nums[i]+nums[j]+nums[k]===0){
triplets.push([nums[i],nums[j],nums[k]]);
j++;
// Never let j refer to the same value twice (in an output) to avoid duplicates
while(j<k&&nums[j]===nums[j-1]){
j++;
}
}elseif(nums[i]+nums[j]+nums[k]<0){
j++;
}else{
k--;
}
}
}
returntriplets;
};
console.log(threeSum([-1,0,1,2,-1,-4]));
console.log(threeSum([]));