4Sum

medium

Find all unique quadruplets that sum to target

Four Sum

Key Insight

Fix two numbers with nested loops, then use converging two pointers for the remaining pair. Sort + skip duplicates.

Step 1Sort Array
Sorted, target = 0
-2
0
-1
1
0
2
1
3
2
4

Sort array. Target=0. Fix two outer indices, use two pointers inside.

1 / 6

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Four Sum

Fix two numbers with nested loops, then use converging two pointers for the remaining pair. Sort + skip duplicates.

  1. Sort Array

    Sort array. Target=0. Fix two outer indices, use two pointers inside.

  2. First Window

    Fix i=0 (-2), j=1 (-1). left=2, right=4. Sum=-2+-1+0+2=-1 < 0, left++.

  3. Quadruplet Found

    left=3, right=4. Sum=-2+-1+1+2=0 ✓ Found [-2,-1,1,2]!

  4. Skip Duplicates

    Skip duplicates, advance pointers. Move to next j. Continue searching.

  5. Continue Search

    i=0, j=2 (0), left=3, right=4. Sum=-2+0+1+2=1 > 0, right--.

  6. Result

    Only quadruplet summing to 0 is [-2,-1,1,2].