Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find all unique quadruplets that sum to a target

Return all unique 4-number combinations from an array that add up to a target value. Use sorting, two-pointer scanning and deduplication.

Python practice25 minHashing & SetsAdvancedLast updated March 26, 2026

Problem statement

Given an array nums and an integer target, return a list of all unique quadruplets [a, b, c, d] such that a + b + c + d == target. The solution set must not contain duplicate quadruplets. Aim for an algorithm with reasonable performance (O(n^3) worst-case) using sorting and two-pointer technique for the inner loops.

Task

Practice multi-pointer scanning and duplicate avoidance to find all unique quadruplets (4-sum) efficiently using sorting and hashing principles.

Examples

Example 1

Input

four_sum([1, 0, -1, 0, -2, 2], 0)

Output

[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]

These are the unique quadruplets summing to 0, sorted lexicographically.

Input format

A list of integers nums and an integer target

Output format

A list of lists; each inner list is a quadruplet of integers. Quadruplets and the outer list should be sorted for deterministic output.

Constraints

0 <= len(nums) <= 200; integers may be negative; avoid duplicate quadruplets; O(n^3) approaches with two pointers are acceptable for this exercise

Samples

Sample 1

Input

[1, 0, -1, 0, -2, 2], target=0

Output

[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]

Classic example producing three unique quadruplets.