3Sum

medium

Find all unique triplets that sum to zero

3Sum

Key Insight

Sort first. Fix one element, use two pointers for remaining two. Skip duplicates.

Step 1Sort Array
Sorted for two-pointer
-4
0
-1
1
-1
2
0
3
1
4
2
5

[-1, 0, 1, 2, -1, -4] → [-4, -1, -1, 0, 1, 2]

1 / 5

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: 3Sum

Sort first. Fix one element, use two pointers for remaining two. Skip duplicates.

  1. Sort Array

    [-1, 0, 1, 2, -1, -4] → [-4, -1, -1, 0, 1, 2]

  2. Fix First Element

    Fix i=0 (value -4). Use two pointers for rest.

  3. Next Fixed Element

    Fix i=1 (value -1). Now search for sum = 1.

  4. Found Triplet!

    [-1, -1, 2] sums to 0. Skip duplicates, continue.

  5. Result

    Found triplets: [[-1,-1,2], [-1,0,1]]