Four Sum Problem All Unique Quadruplets in DSA C++ - Time & Space Complexity
We want to understand how the time needed grows when finding all groups of four numbers that add up to a target.
How does the work increase as the list of numbers gets bigger?
Analyze the time complexity of the following code snippet.
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int>> result;
int n = nums.size();
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.push_back({nums[i], nums[j], nums[left], nums[right]});
left++; right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return result;
}
This code finds all sets of four numbers in the list that add up to the target value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two nested loops plus a two-pointer scan inside the innermost loop.
- How many times: Outer loop runs about n times, second loop about n times, and the two-pointer scan runs up to n times per inner loop.
As the list size grows, the number of operations grows roughly as the cube of the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1,000 |
| 100 | About 1,000,000 |
| 1000 | About 1,000,000,000 |
Pattern observation: The work grows very fast, roughly like n³.
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 more.
[X] Wrong: "The time complexity is O(n⁴) because there are four numbers to pick."
[OK] Correct: The innermost two-pointer scan is linear, not a full loop, so it reduces one level of nesting, making it O(n³) instead of O(n⁴).
Understanding this time complexity helps you explain how nested loops and two-pointer techniques combine, a common pattern in coding challenges.
"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 all unique sets of four numbers in an array that add up to a specific target sum.Step 2: Identify the goal
The goal is to find quadruplets (groups of four numbers) that sum exactly to the target, without duplicates.Final Answer:
Find all unique quadruplets in an array that sum up to a target value -> Option AQuick Check:
Four Sum Problem = Find quadruplets summing to target [OK]
- Confusing with pair or triplet sum problems
- Ignoring uniqueness of quadruplets
- Trying to sort only without finding quadruplets
Solution
Step 1: Understand the data structure needed
We need to store multiple quadruplets, each is a vector of 4 integers, so a vector of vector<int> is suitable.Step 2: Check each option
std::vector quadruplets; declares a vector of vector<int>, perfect for storing multiple quadruplets. std::vector<int> quadruplets(4); creates a single vector of size 4, not multiple quadruplets. std::vector<int> quadruplets = {4}; initializes a vector with one element 4, incorrect. std::vector> quadruplets; uses pairs, which store only two integers, not four.Final Answer:
std::vector quadruplets; -> Option BQuick Check:
Use vector of vector<int> for quadruplets [OK]
- Using vector<int> for multiple quadruplets
- Using pairs instead of quadruplets
- Initializing vector with wrong size or values
{1, 0, -1, 0, -2, 2} and target 0?
std::vector<int> nums = {1, 0, -1, 0, -2, 2};
int target = 0;
// Assume fourSum function returns all unique quadruplets
auto result = fourSum(nums, target);
for (auto &quad : result) {
for (int num : quad) std::cout << num << " ";
std::cout << std::endl;
}Solution
Step 1: Sort the array and find quadruplets summing to target 0
Sorted array: [-2, -1, 0, 0, 1, 2]. The unique quadruplets summing to 0 are [-2, -1, 1, 2], [-2, 0, 0, 2], and [-1, 0, 0, 1].Step 2: Verify output matches quadruplets
[-2 -1 1 2] [-2 0 0 2] [-1 0 0 1] lists exactly these three quadruplets. Options A, C, and D have incorrect quadruplets or sums.Final Answer:
[-2 -1 1 2] [-2 0 0 2] [-1 0 0 1] -> Option AQuick Check:
Unique quadruplets summing to 0 = [-2 -1 1 2] [-2 0 0 2] [-1 0 0 1] [OK]
- Not sorting array before searching
- Including duplicate quadruplets
- Missing some valid quadruplets
std::vector fourSum(std::vector<int>& nums, int target) {
std::vector result;
std::sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); ++i) {
for (int j = i + 1; j < nums.size(); ++j) {
int left = j + 1, right = nums.size() - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
result.push_back({nums[i], nums[j], nums[left], nums[right]});
++left; --right;
} else if (sum < target) {
++left;
} else {
--right;
}
}
}
}
return result;
}Solution
Step 1: Analyze duplicate handling in loops
The code does not skip duplicates for i, j, left, or right indices, so it can add the same quadruplet multiple times.Step 2: Check other parts for errors
Sorting is correct, left and right pointers are initialized properly, and return is after loops. So these are not bugs.Final Answer:
Does not skip duplicate quadruplets, causing repeated results -> Option DQuick Check:
Missing duplicate checks = Does not skip duplicate quadruplets, causing repeated results [OK]
- Not skipping duplicates for i, j, left, right
- Returning result too early
- Incorrect pointer initialization
nums = {2, 2, 2, 2, 2} and target 8, how many unique quadruplets does the Four Sum algorithm find, and what are they?Solution
Step 1: Understand the input and target
All elements are 2, and target is 8. Sum of four 2s is 8, so quadruplet [2, 2, 2, 2] is valid.Step 2: Consider uniqueness
Even though multiple combinations exist, they are duplicates. The algorithm returns only one unique quadruplet.Final Answer:
1 quadruplet: [2, 2, 2, 2] -> Option CQuick Check:
All 2s sum to 8 once uniquely [OK]
- Counting duplicate quadruplets multiple times
- Assuming no quadruplets because of repeated numbers
- Confusing number of combinations with unique quadruplets
Ready to prove it?
Pass the test and this pattern moves unknown
