Array Presets (Auto-Sorted)
Algorithm Loop
Found Triplets
Live Console Log
Live Sum Calculation
3 Sum Algorithm
The 3 Sum problem requires finding all unique triplets in an array that sum up to
zero: nums[i] + nums[j] + nums[k] == 0. While a brute-force approach takes $O(N^3)$
time, we can optimize it to $O(N^2)$ Time and $O(1)$ Space by
sorting the array and using the Two-Pointer technique.
1. Sort & Anchor
First, sort the array. Then, iterate through with pointer i. This acts as our
fixed "anchor". For each i, the problem reduces to finding a 2-Sum equal to
-nums[i].
2. Two Pointers
Set left = i + 1 and right = n - 1. If the sum is too low (< 0),
increment left. If it's too high (> 0), decrement right. If it
equals 0, we found a triplet!
3. Skip Duplicates
To ensure unique triplets, we must aggressively skip duplicate values. We check
nums[i] == nums[i-1], and when a match is found, we bypass adjacent identical
values for left and right.
Algorithm Implementation
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
// 1. Sort the array
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
// Skip duplicate anchors
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
// Skip duplicates for left and right
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++; // Need a larger sum
} else {
right--; // Need a smaller sum
}
}
}
return res;
}
}
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = nums.size() - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
res.push_back({nums[i], nums[left], nums[right]});
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return res;
}
};
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, len(nums) - 1
while left < right:
s = nums[i] + nums[left] + nums[right]
if s == 0:
res.append([nums[i], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
elif s < 0:
left += 1
else:
right -= 1
return res