Four Sum Problem All Unique Quadruplets in DSA C# - Time & Space Complexity
We want to understand how the time needed grows when finding all unique sets 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.
public IList> FourSum(int[] nums, int target) {
Array.Sort(nums);
var result = new List>();
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(new List{nums[i], nums[j], nums[left], nums[right]});
left++; right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return result;
}
This code finds all unique quadruplets in the array that sum to the target by sorting and using two nested loops plus a two-pointer approach.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The nested loops over i and j, and the two-pointer while loop inside.
- How many times: Outer loop runs about n times, second loop about n times, and the two-pointer loop runs up to n times in total for each pair.
As the input size grows, the number of operations grows roughly with 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 doubles, operations increase roughly eight times (cube growth).
Time Complexity: O(n³)
This means the time needed grows roughly with the cube of the input size, so tripling the input makes the work about 27 times bigger.
[X] Wrong: "The time complexity is O(n⁴) because there are four numbers to pick."
[OK] Correct: The two-pointer approach inside the loops reduces one loop, so the complexity is O(n³), not O(n⁴).
Understanding this time complexity helps you explain how nested loops and pointers affect performance, a key skill in solving array problems efficiently.
"What if we replaced the two-pointer approach with another nested loop? 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: Differentiate from other problems
Unlike sorting or finding maximum, this problem focuses on quadruplets and their sums, not individual elements or pairs.Final Answer:
Find all unique quadruplets in an array that sum up to a target value -> Option DQuick Check:
Four Sum Problem = Find quadruplets with target sum [OK]
- Confusing with sorting or max element problems
- Looking for pairs instead of quadruplets
- Ignoring uniqueness of quadruplets
Solution
Step 1: Identify the data structure for storing quadruplets
Each quadruplet is a list of 4 integers, so a list of lists is needed to store multiple quadruplets.Step 2: Match with C# syntax
UsingList<List<int>>correctly represents multiple quadruplets, unlike a single list or dictionary.Final Answer:
var quadruplets = new List<List<int>>(); -> Option AQuick Check:
Use List of List for quadruplets [OK]
- Using List<int> for multiple quadruplets
- Using Dictionary instead of List
- Using fixed-size array for dynamic quadruplets
nums = [1, 0, -1, 0, -2, 2] and target 0, what does FourSum(nums, 0) return?Assuming
FourSum returns all unique quadruplets that sum to target.Solution
Step 1: Sort and find quadruplets summing to 0
Sorting nums gives [-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 uniqueness and completeness
All quadruplets are unique and sum exactly to 0, matching the expected output.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(new List<int> { 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 adds quadruplets without skipping duplicates, so repeated quadruplets can appear in the result.Step 2: Check other parts
Left and right pointers are correctly initialized; loop ranges are valid; sorting is assumed done before this snippet.Final Answer:
No check to skip duplicate quadruplets causing duplicates in result -> Option AQuick Check:
Missing duplicate skip = No check to skip duplicate quadruplets causing duplicates in result [OK]
- Not skipping duplicates for i, j, left, right
- Assuming sorting is done inside the loop
- Incorrect pointer updates causing infinite loops
nums = [2, 2, 2, 2, 2] and target 8, what is the correct output of the Four Sum Problem algorithm that finds all unique quadruplets?Solution
Step 1: Understand the input and target
All elements are 2, and target is 8, so quadruplets of four 2's sum to 8.Step 2: Identify unique quadruplets
Only one unique quadruplet [2, 2, 2, 2] exists despite duplicates in input.Final Answer:
[[2, 2, 2, 2]] -> Option BQuick Check:
Only one unique quadruplet sums to 8 [OK]
- Counting duplicate quadruplets multiple times
- Returning empty list when quadruplet exists
- Returning triplets instead of quadruplets
Ready to prove it?
Pass the test and this pattern moves unknown
