Skip to content

Commit 7f34974

Browse files
authored
Create 3Sum.java
1 parent 459b5d4 commit 7f34974

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

TwoPointer/3Sum.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
//LeetCode 15. 3Sum
2+
//Question - https://leetcode.com/problems/3sum/
3+
4+
class Solution {
5+
public List<List<Integer>> threeSum(int[] nums) {
6+
int n = nums.length;
7+
List<List<Integer>> res = new ArrayList<>();
8+
9+
//to help facilitate finding the triplets
10+
Arrays.sort(nums);
11+
12+
//consider nums[i] as the first element of the triplet
13+
for(int i = 0 ; i < n - 2 ; i++){
14+
//the array is sorted, if the first element is greater than 0 then all
15+
//other elements after the current element would be positive as well.
16+
//The sum can never be 0.
17+
if(nums[i] > 0) break;
18+
19+
//skip the current number if it has already been used as the first element
20+
if(i > 0 && nums[i] == nums[i-1]) continue;
21+
22+
23+
//logic to find the other two elements of the triplets
24+
int low = i+1;
25+
int high = n - 1;
26+
while(low < high){
27+
int sum = nums[i] + nums[low] + nums[high];
28+
29+
//if sum of the chosen elements is < 0
30+
if(sum < 0) low++;
31+
//if sum of the chosen elements is > 0
32+
else if(sum > 0) high--;
33+
//the sum is 0
34+
else{
35+
//append the current triplet
36+
res.add(Arrays.asList(nums[i], nums[low], nums[high]));
37+
38+
//keeping the first element fixed(i) and exploring other numbers
39+
//for the other two positions in the triplet
40+
//loops to avoid duplicates
41+
while(low < high && nums[low] == nums[low + 1]) low++;
42+
while(low < high && nums[high] == nums[high - 1]) high--;
43+
44+
//need to update because after the loop the pointers point to last
45+
//location of the repeated number
46+
low++;
47+
high--;
48+
}
49+
}
50+
51+
}
52+
return res;
53+
}
54+
}

0 commit comments

Comments
 (0)