Three Sum Problem All Unique Triplets in DSA Java - Time & Space Complexity
We want to understand how the time needed grows when finding all unique triplets in an array that sum to zero.
How does the number of steps change as the array gets bigger?
Analyze the time complexity of the following code snippet.
public List> threeSum(int[] nums) {
Arrays.sort(nums);
List> result = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.add(Arrays.asList(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 result;
}
This code finds all unique triplets in the array that add up to zero by sorting and using two pointers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer loop runs through each element, and inside it, a two-pointer scan moves through the remaining elements.
- How many times: The outer loop runs about n times, and for each, the inner while loop can run up to n times in total.
As the array size grows, the number of steps grows roughly with the square of the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 steps |
| 100 | About 10,000 steps |
| 1000 | About 1,000,000 steps |
Pattern observation: The steps grow roughly by the square of the input size, meaning if the input size doubles, the work roughly quadruples.
Time Complexity: O(n²)
This means the time needed grows roughly with the square of the input size, so doubling the input makes the work about four times bigger.
[X] Wrong: "The time complexity is O(n³) because there are three nested loops."
[OK] Correct: The code uses sorting and two pointers inside a single loop, not three full nested loops, so the inner loops together run in linear time per outer loop, making it O(n²).
Understanding this time complexity helps you explain how your solution scales and shows you can analyze nested loops carefully, a key skill in interviews.
"What if the input array was not sorted first? How would the time complexity change?"
Practice
Three Sum Problem in data structures and algorithms?Solution
Step 1: Understand the problem statement
The Three Sum Problem asks to find all unique sets of three numbers in an array whose sum is zero.Step 2: Identify the goal
The goal is to find triplets (three numbers) that add up exactly to zero without duplicates.Final Answer:
Find all unique triplets in an array that sum to zero -> Option CQuick Check:
Three Sum Problem = Find triplets summing to zero [OK]
- Thinking it finds pairs instead of triplets
- Assuming it sorts the array only
- Looking for maximum sum instead of zero sum
Solution
Step 1: Check Java array initialization syntax
In Java, arrays are initialized withnew int[]{...}or directly with curly braces during declaration.Step 2: Validate each option
int[] nums = new int[]{-1, 0, 1, 2, -1, -4}; uses correct syntax:int[] nums = new int[]{-1, 0, 1, 2, -1, -4};. Others have syntax errors.Final Answer:
int[] nums = new int[]{-1, 0, 1, 2, -1, -4}; -> Option DQuick Check:
Correct Java array syntax = int[] nums = new int[]{-1, 0, 1, 2, -1, -4}; [OK]
- Using parentheses instead of braces
- Missing 'new' keyword
- Declaring array without type
import java.util.*;
public class ThreeSum {
public static List threeSum(int[] nums) {
List res = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, 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]));
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;
}
public static void main(String[] args) {
int[] nums = {-1, 0, 1, 2, -1, -4};
System.out.println(threeSum(nums));
}
}Solution
Step 1: Sort and iterate through the array
The array after sorting is [-4, -1, -1, 0, 1, 2]. The code skips duplicates and uses two pointers to find triplets summing to zero.Step 2: Identify unique triplets summing to zero
Triplets found are [-1, -1, 2] and [-1, 0, 1]. These are added to the result list.Final Answer:
[[-1, -1, 2], [-1, 0, 1]] -> Option AQuick Check:
Unique triplets summing zero = [[-1, -1, 2], [-1, 0, 1]] [OK]
- Not sorting array before two-pointer approach
- Including duplicate triplets
- Incorrect pointer movement causing wrong sums
public List threeSum(int[] nums) {
List res = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (nums[i] == nums[i + 1]) continue;
int left = i + 1, 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]));
left++;
right--;
} else if (sum < 0) left++;
else right--;
}
}
return res;
}Solution
Step 1: Identify the duplicate skipping condition
The code incorrectly checksnums[i] == nums[i + 1]which can cause index out of bounds and wrong duplicate skipping.Step 2: Correct duplicate skipping logic
The correct check isif (i > 0 && nums[i] == nums[i - 1]) continue;to skip duplicates properly without errors.Final Answer:
Change if (nums[i] == nums[i + 1]) continue; to if (i > 0 && nums[i] == nums[i - 1]) continue; -> Option BQuick Check:
Proper duplicate skip check = Changeif (nums[i] == nums[i + 1]) continue;toif (i > 0 && nums[i] == nums[i - 1]) continue;[OK]
- Checking next element instead of previous for duplicates
- Not sorting array before duplicate check
- Incorrect pointer conditions causing infinite loops
nums = [0, 0, 0, 0], what is the correct output of the Three Sum Problem algorithm that finds all unique triplets summing to zero?Solution
Step 1: Understand the input array with duplicates
The array has four zeros. The algorithm must find unique triplets summing to zero.Step 2: Identify unique triplets
Only one unique triplet exists: [0, 0, 0]. Duplicates are skipped to avoid repeated triplets.Final Answer:
[[0, 0, 0]] -> Option AQuick Check:
Unique zero triplet = [[0, 0, 0]] [OK]
- Returning multiple identical triplets
- Returning empty list thinking no sum possible
- Returning pairs instead of triplets
Ready to prove it?
Pass the test and this pattern moves unknown
