Four Sum Problem All Unique Quadruplets in DSA Javascript - 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 list gets bigger.
How does the number of steps change when the input list grows?
Analyze the time complexity of the following code snippet.
function fourSum(nums, target) {
nums.sort((a, b) => a - b);
const quadruplets = [];
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 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 a two-pointer scan inside the innermost loop.
- How many times: The outer loop runs about n times, the next loop about n times, and the two-pointer scan runs up to n times for each pair, making the main work repeat roughly n x n x n times.
As the input size grows, the number of steps 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 increases 10 times, operations increase about 1,000 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: "Since there are four numbers, the time complexity must be O(n⁴)."
[OK] Correct: The two-pointer method reduces the innermost search from a loop to a linear scan, so the complexity is O(n³), not O(n⁴).
Understanding this problem's time complexity helps you explain how nested loops and clever scanning affect performance, a skill useful in many coding challenges.
"What if we replaced the two-pointer scan with a nested loop 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 us to find all unique groups of four numbers in an array that add up to a specific target sum.Step 2: Differentiate from other problems
This is different from sorting, finding max, or counting pairs because it specifically looks for quadruplets with a sum equal to the target.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 sorting or max element problems
- Looking for pairs instead of quadruplets
- Ignoring uniqueness of quadruplets
nums in JavaScript before solving the Four Sum Problem?Solution
Step 1: Understand JavaScript sort behavior
By default,nums.sort()sorts elements as strings, which can give wrong order for numbers.Step 2: Use numeric comparison function
Usingnums.sort((a, b) => a - b)sorts numbers in ascending order correctly, which is needed for the Four Sum algorithm.Final Answer:
nums.sort((a, b) => a - b) -> Option DQuick Check:
Numeric ascending sort = nums.sort((a, b) => a - b) [OK]
- Using default sort without compare function
- Using descending order when ascending is needed
- Using non-existent method like sorted()
const nums = [1, 0, -1, 0, -2, 2]; const target = 0; // Assume findFourSum returns all unique quadruplets summing to target const result = findFourSum(nums, target); console.log(result);
Given
findFourSum correctly implements the Four Sum algorithm, what is the expected output?Solution
Step 1: Sort the array and find quadruplets
Sorted array is [-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 quadruplets sum to target
Each quadruplet sums to 0, matching the target, and all are unique sets.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 processing
- Including duplicate quadruplets
- Incorrect quadruplet sums
function fourSum(nums, target) {
nums.sort();
const quadruplets = [];
for (let i = 0; i < nums.length - 3; i++) {
for (let j = i + 1; j < nums.length - 2; j++) {
let left = j + 1;
let 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: Check sorting method
The code usesnums.sort()without a compare function, which sorts elements as strings, causing incorrect order for numbers.Step 2: Impact on algorithm correctness
Incorrect sorting leads to wrong quadruplets or missed solutions because the two-pointer approach depends on sorted numeric order.Final Answer:
The array is not sorted numerically before processing -> Option BQuick Check:
Missing numeric sort compare function = The array is not sorted numerically before processing [OK]
- Using default sort without compare function
- Not returning the result array
- Incorrect loop ranges (not here though)
- Wrong sum calculation (correct here)
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. Four 2's sum to 8 exactly.Step 2: Identify unique quadruplets
Even though there are multiple 2's, only one unique quadruplet [2, 2, 2, 2] exists that sums to 8.Final Answer:
[[2, 2, 2, 2]] -> Option CQuick Check:
Unique quadruplet summing to 8 = [[2, 2, 2, 2]] [OK]
- Listing duplicate quadruplets multiple times
- Returning empty when quadruplet exists
- Confusing triplets with quadruplets
Ready to prove it?
Pass the test and this pattern moves unknown
