Four Sum Problem All Unique Quadruplets in DSA Typescript - 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.
function fourSum(nums: number[], target: number): number[][] {
nums.sort((a, b) => a - b);
const quadruplets: number[][] = [];
const n = nums.length;
for (let i = 0; i < n - 3; i++) {
for (let j = i + 1; j < n - 2; j++) {
let left = j + 1, right = n - 1;
while (left < right) {
const sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum === target) {
quadruplets.push([nums[i], nums[j], nums[left], nums[right]]);
left++;
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return quadruplets;
}
This code finds all sets of four numbers that add up to the target by sorting and using nested loops with two pointers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two nested loops plus a two-pointer scan (linear time O(n)) inside the inner loop.
- How many times: Outer loop runs about n times, second loop about n times, and inside the two-pointer scan moves across the remaining elements (~n steps).
As the list size grows, the number of operations grows roughly with the cube of the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10³ ≈ 1,000 |
| 100 | About 100³ = 1,000,000 |
| 1000 | About 1000³ = 1,000,000,000 |
Pattern observation: The work grows very fast, roughly like n³, because of the nested loops and scanning.
Time Complexity: O(n³)
This means if the list doubles in size, the time needed grows about eight times, due to the two nested loops and linear scanning.
[X] Wrong: "The time complexity is O(n⁴) because there are four numbers to pick."
[OK] Correct: The innermost two numbers are found using a two-pointer scan, which runs in linear time, not a full loop, so the total is O(n³), not O(n⁴).
Understanding this complexity helps you explain how nested loops and two-pointer techniques combine, a skill useful for many array problems.
"What if we used a hash map to store pairs sums instead of two pointers? 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 given target sum.Step 2: Identify the goal
The goal is to return all quadruplets without duplicates that sum to the target value.Final Answer:
Find all unique quadruplets in an array that sum up to a target value -> Option BQuick Check:
Four Sum Problem = Find quadruplets summing to target [OK]
- Confusing with two sum or three sum problems
- Ignoring uniqueness of quadruplets
- Trying to find maximum or minimum instead of sum
Solution
Step 1: Analyze the function parameters and return type
The function should take an array of numbers and a target number, and return an array of quadruplets (arrays of numbers).Step 2: Match the correct signature
function fourSum(nums: number[], target: number): number[][] matches this: input is number array and target number, output is array of number arrays.Final Answer:
function fourSum(nums: number[], target: number): number[][] -> Option DQuick Check:
Correct input/output types = function fourSum(nums: number[], target: number): number[][] [OK]
- Wrong parameter order or types
- Returning single number instead of array of quadruplets
- Using string types instead of number
const nums = [1, 0, -1, 0, -2, 2];
const target = 0;
console.log(fourSum(nums, target));
function fourSum(nums: number[], target: number): number[][] {
nums.sort((a, b) => a - b);
const quadruplets: number[][] = [];
for (let i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
for (let j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] === nums[j - 1]) continue;
let left = j + 1, right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum === target) {
quadruplets.push([nums[i], nums[j], 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 < target) {
left++;
} else {
right--;
}
}
}
}
return quadruplets;
}Solution
Step 1: Sort the array and initialize variables
The array after sorting is [-2, -1, 0, 0, 1, 2]. We use nested loops and two pointers to find quadruplets summing to 0.Step 2: Find all unique quadruplets summing to target
By iterating and skipping duplicates, the quadruplets found 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 CQuick Check:
Unique quadruplets summing to 0 = [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]] [OK]
- Not sorting array before processing
- Not skipping duplicates causing repeated quadruplets
- Incorrect pointer movement leading to missed quadruplets
function fourSum(nums: number[], target: number): number[][] {
nums.sort((a, b) => a - b);
const quadruplets: number[][] = [];
for (let i = 0; i < nums.length - 3; i++) {
for (let j = i + 1; j < nums.length - 2; j++) {
let left = j + 1, right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum === target) {
quadruplets.push([nums[i], nums[j], nums[left], nums[right]]);
left++;
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return quadruplets;
}Solution
Step 1: Review duplicate handling in loops
The code does not skip duplicate values for i, j, left, or right indices, which can cause repeated quadruplets in the result.Step 2: Identify missing duplicate checks
Proper skipping of duplicates after pushing quadruplets and in outer loops is needed to ensure uniqueness.Final Answer:
Missing checks to skip duplicate elements causing repeated quadruplets -> Option AQuick Check:
Duplicate skipping missing = Missing checks to skip duplicate elements causing repeated quadruplets [OK]
- Not skipping duplicates in outer loops
- Not skipping duplicates after pushing quadruplet
- Assuming sorting fixes duplicates automatically
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: Understand the input and target
The array has five identical elements 2, and the target sum is 8.Step 2: Find unique quadruplets summing to 8
Only one unique quadruplet [2, 2, 2, 2] sums to 8. Even though elements repeat, quadruplets must be unique sets.Final Answer:
[[2, 2, 2, 2]] -> Option AQuick Check:
Unique quadruplet with sum 8 = [[2, 2, 2, 2]] [OK]
- Returning duplicate quadruplets multiple times
- Returning empty list incorrectly
- Confusing triplets with quadruplets
Ready to prove it?
Pass the test and this pattern moves unknown
