How to Find Four Sum Quadruplets in Python (Sorted Demo)
Find all unique quadruplets in a sorted array that sum to a target, with duplicate skipping.
Python code
35 linesdef four_sum(nums, target):
nums.sort()
result = []
n = len(nums)
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
left, right = j + 1, n - 1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == target:
result.append([nums[i], nums[j], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < target:
left += 1
else:
right -= 1
return result
if __name__ == "__main__":
nums = [1, 0, -1, 0, -2, 2]
target = 0
print(f"Input: {nums}, target = {target}")
print("Quadruplets:", four_sum(nums, target))
print("Sorted input:", sorted(nums))
Output
Input: [1, 0, -1, 0, -2, 2], target = 0
Quadruplets: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
Sorted input: [-2, -1, 0, 0, 1, 2]
How it works
Sort the array first so the two-pointer technique works. Fix two indices (i and j) then move left and right pointers toward each other. When the sum matches, record the quadruplet and skip duplicate values on all sides. If the sum is too low advance left, if too high move right back. This runs in O(n³) time with O(1) extra space.
Common mistakes
- Forgetting to sort the input before using two pointers
- Not skipping duplicates for the first two fixed indices
- Not advancing both left and right pointers after finding a match
- Incorrect bounds when n < 4 (missing early return)
Variations
- Use a hash map to store pair sums for a O(n²) time solution
- Return tuples or set of tuples instead of lists for automatic deduplication
Real-world use cases
- Finding combinations of product prices that hit a budget in pricing engines.
- Checking if a transaction set can sum to a target in fraud detection systems.
- Solving subset-sum style problems in scheduling or resource allocation tools.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.