Four Sum Problem All Unique Quadruplets in DSA Python - 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 input list gets bigger.
How does the number of steps change when the list size increases?
Analyze the time complexity of the following code snippet.
nums.sort()
quadruplets = []
n = len(nums)
for i in range(n - 3):
for j in range(i + 1, n - 2):
left, right = j + 1, n - 1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == target:
quadruplets.append([nums[i], nums[j], nums[left], nums[right]])
left += 1
right -= 1
elif total < target:
left += 1
else:
right -= 1
This code finds all groups of four numbers in a list that add up to a given target value.
- Primary operation: Nested loops and a two-pointer scan inside the innermost loop.
- How many times: The outer two loops run roughly n² times, and for each pair, the two-pointer scan runs up to n times.
As the list size grows, the number of steps grows much faster because of the nested loops and the two-pointer scan inside.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10³ = 1,000 steps |
| 100 | About 100³ = 1,000,000 steps |
| 1000 | About 1000³ = 1,000,000,000 steps |
Pattern observation: The steps grow roughly by the cube of the input size, so doubling the list size makes the work about eight times bigger.
Time Complexity: O(n³)
This means the time needed grows roughly with the cube of the input size, so bigger lists take much more time.
[X] Wrong: "Because we use two pointers inside, the time complexity is O(n²)."
[OK] Correct: The two-pointer scan runs inside two nested loops, so the total work multiplies, making it O(n³), not just O(n²).
Understanding this time complexity helps you explain how nested loops and scanning affect performance, a key skill in solving real problems efficiently.
"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 (quadruplets) in an array that add up to a given target sum.Step 2: Identify the goal
The goal is not sorting or counting pairs but to find quadruplets with a specific sum without duplicates.Final Answer:
Find all unique quadruplets in an array that sum up to a target value -> Option AQuick Check:
Four Sum = unique quadruplets summing to target [OK]
- Confusing Four Sum with Two Sum or Three Sum problems
- Thinking the problem is about sorting or counting pairs
- Ignoring the uniqueness of quadruplets
Solution
Step 1: Identify the correct data structure for storing multiple quadruplets
Quadruplets are multiple groups of four numbers, so a list is suitable to store them.Step 2: Check the initialization syntax
Using[]initializes an empty list, which is correct. Curly braces{}create a dictionary, parentheses()create a tuple, andset()creates a set which is unordered and not ideal here.Final Answer:
quadruplets = [] -> Option BQuick Check:
Empty list for quadruplets = [] [OK]
- Using {} which creates a dictionary, not a list
- Using () which creates an immutable tuple
- Using set() which is unordered and may lose duplicates
nums = [1, 0, -1, 0, -2, 2]
target = 0
# After sorting
nums.sort()
quadruplets = []
for i in range(len(nums)-3):
for j in range(i+1, len(nums)-2):
left, right = j+1, len(nums)-1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == target:
quadruplets.append([nums[i], nums[j], nums[left], nums[right]])
left += 1
right -= 1
elif total < target:
left += 1
else:
right -= 1
print(quadruplets)Solution
Step 1: Sort the array and understand the loops
Sorted nums = [-2, -1, 0, 0, 1, 2]. The nested loops and two-pointer approach check all quadruplets summing to target 0.Step 2: Identify quadruplets that sum to zero
Valid quadruplets are [-2, -1, 1, 2], [-2, 0, 0, 2], and [-1, 0, 0, 1]. These are appended to quadruplets list.Final Answer:
[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]] -> Option CQuick Check:
Sum quadruplets = 0 matches output [OK]
- Not sorting the array before processing
- Missing some quadruplets due to pointer errors
- Appending duplicates without checks
nums = [2, 2, 2, 2, 2]
target = 8
nums.sort()
quadruplets = []
for i in range(len(nums)-3):
for j in range(i+1, len(nums)-2):
left, right = j+1, len(nums)-1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == target:
quadruplets.append([nums[i], nums[j], nums[left], nums[right]])
left += 1
right -= 1
elif total < target:
left += 1
else:
right -= 1
print(quadruplets)Solution
Step 1: Identify the problem with duplicates
The code appends quadruplets but does not skip duplicates, so it will add the same quadruplet multiple times.Step 2: Fix by skipping duplicates
Adding checks to skip duplicate values for i, j, left, and right indices after finding a quadruplet prevents repeated quadruplets.Final Answer:
Add checks to skip duplicates for i, j, left, and right indices -> Option AQuick Check:
Skipping duplicates avoids repeated quadruplets [OK]
- Not skipping duplicates causing repeated quadruplets
- Using set without sorting can cause unordered results
- Removing sorting breaks two-pointer logic
nums = [1, 0, -1, 0, -2, 2, 2] and target 2, which of the following lists contains all unique quadruplets that sum to the target?Solution
Step 1: Sort the array and find quadruplets summing to 2
Sorted nums = [-2, -1, 0, 0, 1, 2, 2]. We look for quadruplets where sum equals 2.Step 2: Identify valid quadruplets
Valid quadruplets are [-2, 0, 2, 2] (sum = 2) and [-1, 0, 1, 2] (sum = 2). Other options contain invalid or impossible sums.Final Answer:
[[-2, 0, 2, 2], [-1, 0, 1, 2]] -> Option DQuick Check:
Sum quadruplets = 2 matches output [OK]
- Including quadruplets with wrong sums
- Ignoring duplicates or invalid numbers
- Not sorting before searching quadruplets
Ready to prove it?
Pass the test and this pattern moves unknown
