Four Sum Problem All Unique Quadruplets in DSA C - Time & Space Complexity
We want to understand how the time needed to find all unique sets of four numbers that add up to a target grows as the input list grows.
How does the work increase when the list gets bigger?
Analyze the time complexity of the following code snippet.
void fourSum(int* nums, int numsSize, int target) {
qsort(nums, numsSize, sizeof(int), compare);
for (int i = 0; i < numsSize - 3; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
for (int j = i + 1; j < numsSize - 2; j++) {
if (j > i + 1 && nums[j] == nums[j-1]) continue;
int left = j + 1, right = numsSize - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
// store quadruplet
left++; right--;
while (left < right && nums[left] == nums[left-1]) left++;
while (left < right && nums[right] == nums[right+1]) right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
}
This code finds all unique groups of four numbers in a sorted 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: Outer loop runs about n times, second loop about n times, and the two-pointer while loop runs up to n times in total for each pair.
As the list size grows, the number of operations grows roughly by the cube of the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1,000 |
| 100 | About 1,000,000 |
| 1000 | About 1,000,000,000 |
Pattern observation: When input size increases 10 times, operations increase about 1000 times, showing cubic growth.
Time Complexity: O(n³)
This means the time needed grows roughly with the cube of the input size, so doubling the input makes the work about eight times bigger.
[X] Wrong: "The time complexity is O(n⁴) because there are four nested loops."
[OK] Correct: The innermost two-pointer loop does not run n times for each iteration; it moves pointers inward, so total work inside is linear, not quadratic, reducing complexity to O(n³).
Understanding this time complexity helps you explain how nested loops and two-pointer techniques combine, a common pattern in coding problems.
"What if we changed the problem to find unique triplets instead of quadruplets? 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 four numbers in an array whose sum equals a target value.Step 2: Identify the expected output
We want all unique sets of four numbers (quadruplets) that add up to the target.Final Answer:
Find all unique quadruplets in an array that sum up to a target value -> Option CQuick Check:
Four Sum = unique quadruplets with target sum [OK]
- Confusing with two or three sum problems
- Ignoring uniqueness of quadruplets
- Trying to find maximum or minimum instead of sum
Solution
Step 1: Check array initialization syntax in C
Arrays in C are initialized with curly braces {} and square brackets [] for declaration.Step 2: Validate each option
int nums[] = {1, 0, -1, 0, -2, 2}; int target = 0; uses correct syntax: int nums[] = { ... }; int nums = {1, 0, -1, 0, -2, 2}; int target = 0; misses brackets, C uses parentheses, D uses square brackets incorrectly.Final Answer:
int nums[] = {1, 0, -1, 0, -2, 2}; int target = 0; -> Option DQuick Check:
Correct C array syntax = int nums[] = {1, 0, -1, 0, -2, 2}; int target = 0; [OK]
- Using parentheses () instead of braces {}
- Missing square brackets [] in declaration
- Using square brackets [] for initialization
int nums[] = {1, 0, -1, 0, -2, 2};
int target = 0;
// Assume function fourSum returns all unique quadruplets
// and prints them as quadruplets separated by spaces
// Output format: a b c d\n for each quadruplet
fourSum(nums, 6, target);
Solution
Step 1: Sort the array
Sorted nums = [-2, -1, 0, 0, 1, 2]Step 2: Find all unique quadruplets summing to 0
Quadruplets are [-2, -1, 1, 2], [-2, 0, 0, 2], and [-1, 0, 0, 1].Final Answer:
-2 -1 1 2 -2 0 0 2 -1 0 0 1 -> Option BQuick Check:
Sum of each quadruplet = 0 [OK]
- Not sorting array before processing
- Including duplicate quadruplets
- Incorrect sum calculation
void fourSum(int* nums, int numsSize, int target) {
for (int i = 0; i < numsSize - 3; i++) {
for (int j = i + 1; j < numsSize - 2; j++) {
int left = j + 1, right = numsSize - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
printf("%d %d %d %d\n", nums[i], nums[j], nums[left], nums[right]);
left++;
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
}Solution
Step 1: Analyze duplicate handling
The code prints quadruplets but does not skip duplicates, so repeated quadruplets appear.Step 2: Check other parts
Left and right pointers are correctly initialized; loop ranges are valid; return statement is not needed in void function.Final Answer:
No check to skip duplicate quadruplets causing repeated outputs -> Option AQuick Check:
Duplicates not skipped = No check to skip duplicate quadruplets causing repeated outputs [OK]
- Not skipping duplicates for i, j, left, right
- Incorrect pointer updates causing infinite loops
- Accessing array out of bounds
nums = {2, 2, 2, 2, 2} and target 8. How many unique quadruplets sum to the target, and what are they?Solution
Step 1: Understand array and target
All elements are 2, target is 8, so quadruplet sum must be 2+2+2+2=8.Step 2: Count unique quadruplets
Even though multiple indices exist, the quadruplet values are the same, so only one unique quadruplet exists: [2, 2, 2, 2].Final Answer:
1 quadruplet: [2, 2, 2, 2] -> Option AQuick Check:
Sum 2+2+2+2=8 unique quadruplet [OK]
- Counting quadruplets by indices, not unique values
- Assuming multiple quadruplets due to duplicates
- Ignoring uniqueness condition
Ready to prove it?
Pass the test and this pattern moves unknown
