Four Sum Problem All Unique Quadruplets in DSA Java - Time & Space Complexity
We want to understand how the time needed to find all sets of four numbers that add up to a target grows as the input list gets bigger.
How does the number of steps change when the list size increases?
Analyze the time complexity of the following code snippet.
public List> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List> result = new ArrayList<>();
int n = nums.length;
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
int left = j + 1, right = n - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
left++; right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return result;
}
This code finds all groups of four numbers in the array that add up to the target value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops and two-pointer traversal inside the while loop.
- How many times: The outer loop runs about n times, the second loop runs about n times for each outer loop, and the two-pointer while loop runs up to n times for each pair.
As the input size grows, the number of steps grows roughly by the cube of the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1,000 steps |
| 100 | About 1,000,000 steps |
| 1000 | About 1,000,000,000 steps |
Pattern observation: When input size increases 10 times, operations increase about 1,000 times (cube growth).
Time Complexity: O(n³)
This means the time needed grows roughly with the cube of the input size, so if the list doubles, the time increases about eight times.
[X] Wrong: "The time complexity is O(n⁴) because there are four numbers to pick."
[OK] Correct: The two-pointer technique reduces the inner two loops to a single pass, so the complexity is O(n³), not O(n⁴).
Understanding this time complexity helps you explain how nested loops and two-pointer methods combine to affect performance, a useful skill for solving similar problems efficiently.
"What if we replaced the two-pointer approach with two nested loops for the last two numbers? How would the time complexity change?"
Practice
Four Sum Problem in data structures and algorithms?Solution
Step 1: Understand the problem statement
The Four Sum Problem asks to find sets of four numbers in an array that add up to a given target.Step 2: Identify the expected output
We want all unique quadruplets, meaning no repeated sets, that sum exactly to the target.Final Answer:
Find all unique quadruplets in an array that sum up to a target value -> Option AQuick Check:
Four Sum = unique quadruplets summing to target [OK]
- Confusing Four Sum with Two Sum or Three Sum problems
- Ignoring uniqueness of quadruplets
- Trying to find maximum or minimum instead of sum
Solution
Step 1: Check Java syntax for list initialization
Correct generic syntax for a list of lists of integers isList quadruplets = new ArrayList<>();Step 2: Identify errors in other options
List quadruplets = new List<>(); uses raw List without generics and wrong constructor; ArrayList<int> quadruplets = new ArrayList<>(); uses primitive int which is invalid; List<List> quadruplets = new ArrayList(); mixes generics incorrectly.Final Answer:
List quadruplets = new ArrayList<>(); -> Option BQuick Check:
Correct generic list initialization = List quadruplets = new ArrayList<>(); [OK]
- Using raw types without generics
- Trying to use primitive types in generics
- Incorrect constructor calls for List
int[] nums = {1, 0, -1, 0, -2, 2};
int target = 0;
List result = fourSum(nums, target);
System.out.println(result);Assuming
fourSum correctly finds all unique quadruplets summing to target.Solution
Step 1: Sort and find quadruplets summing to zero
Sorted array: [-2, -1, 0, 0, 1, 2]. Quadruplets summing to 0 are [-2,-1,1,2], [-2,0,0,2], and [-1,0,0,1].Step 2: Verify uniqueness and completeness
All quadruplets are unique and sum exactly to target 0. No other quadruplets exist.Final Answer:
[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]] -> Option CQuick Check:
Unique quadruplets sum to 0 = [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]] [OK]
- Not sorting array before processing
- Including duplicate quadruplets
- Missing some valid quadruplets
for (int i = 0; i < nums.length - 3; i++) {
for (int j = i + 1; j < nums.length - 2; j++) {
int left = j + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
left++;
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}Solution
Step 1: Analyze loop and pointer usage
Loops and pointers are correctly set to find quadruplets, and sum calculation is correct.Step 2: Identify missing duplicate skipping
Code lacks checks to skip duplicate values for i, j, left, and right after finding a quadruplet, which can cause duplicate quadruplets in result.Final Answer:
Missing checks to skip duplicate elements for i, j, left, and right -> Option DQuick Check:
Duplicate skipping missing = Missing checks to skip duplicate elements for i, j, left, and right [OK]
- Not skipping duplicates causing repeated quadruplets
- Changing pointers incorrectly inside loops
- Incorrect loop boundaries causing index errors
nums = {2, 2, 2, 2, 2} and target 8, what is the correct output of the Four Sum problem solution that finds all unique quadruplets?Solution
Step 1: Check if quadruplets sum to target
All elements are 2, so quadruplet [2, 2, 2, 2] sums to 8.Step 2: Ensure uniqueness of quadruplets
Even though elements repeat, only one unique quadruplet exists. Duplicates must be avoided.Final Answer:
[[2, 2, 2, 2]] -> Option AQuick Check:
Unique quadruplet summing to 8 = [[2, 2, 2, 2]] [OK]
- Returning duplicate quadruplets multiple times
- Returning empty list when quadruplet exists
- Confusing triple with quadruplet
Ready to prove it?
Pass the test and this pattern moves unknown
