Skip to content

Commit fccf9b6

Browse files
committed
solved 3sum
1 parent f748e28 commit fccf9b6

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

3sum/samcho0608.java

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.List;
4+
5+
// link: https://leetcode.com/problems/3sum/
6+
// difficulty: Medium
7+
class Solution {
8+
// Problem:
9+
// * return: all triplets of elements in nums such that the sum == 0 (indices must differ)
10+
// Solution:
11+
// * Time Complexity: O(N^2)
12+
// * Space Complexity: O(1)
13+
public List<List<Integer>> threeSum(int[] nums) {
14+
// sort for simplicity
15+
// Time Complexity: O(N log N)
16+
Arrays.sort(nums);
17+
18+
List<List<Integer>> answers = new ArrayList<>();
19+
20+
// if there are only positive or only negative numbers, there exist no solution
21+
if(nums[0] > 0 || nums[nums.length-1] < 0) return answers;
22+
23+
24+
25+
// Time Complexity: O(N^2)
26+
// * for loop * inner while loop = O(N) * O(N) = O(N^2)
27+
28+
// nums[i]: first of the triplet
29+
// * skip positive because the other two will also be positive
30+
for(int i = 0; i < nums.length && nums[i] <= 0; i++) {
31+
// skip if same first of the triplet met
32+
if(i != 0 && nums[i] == nums[i-1]) continue;
33+
34+
int numI = nums[i];
35+
36+
int left = i + 1;
37+
int right = nums.length - 1;
38+
39+
// Time Complexity: O(N)
40+
while(left < right) {
41+
int numLeft = nums[left];
42+
int numRight = nums[right];
43+
44+
int sum = numI + numLeft + numRight;
45+
46+
if(sum == 0) {
47+
answers.add(Arrays.asList(numI, numLeft, numRight));
48+
49+
// skip same lefts and rights two prevent duplicate
50+
// * must update both left and right
51+
// * e.g. if only left is moved, newNumLeft = 0 - (numI + numRight) and that can only be numLeft that's already visited
52+
// * Time Complexity: O(1) because there is no actual operation other than skipping
53+
while(left < nums.length && nums[left] == numLeft) left++;
54+
55+
while(right > left && nums[right] == numRight) right--;
56+
} else if(sum > 0) {
57+
right--;
58+
} else {
59+
left++;
60+
}
61+
}
62+
}
63+
64+
return answers;
65+
}
66+
}

0 commit comments

Comments
 (0)