4Sum

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: 4Sum

Approach

Sort the array, then use two nested loops to fix the first two elements. For the remaining two, use converging two pointers. Skip duplicates at every level to ensure unique quadruplets. This reduces the problem from O(n^4) brute force to O(n^3).

Complexity Analysis

Time
O(n^3)
Space
O(1)

Pattern

Two Pointers (Converging) + Sort

Why It Works

Sorting enables efficient duplicate skipping and the two-pointer sum search. Each nesting level fixes one more element, and the innermost two-pointer scan finds all valid pairs in linear time.

Updated Feb 2026