DSA AnimatorDSA animations
3Sum LC #15 Medium Two Pointers · Sorting
Problem

Given an integer array nums, return all triplets [nums[i], nums[j], nums[k]] such that i≠j≠k and nums[i]+nums[j]+nums[k]==0. The solution set must not contain duplicate triplets.

Example 1
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Constraints: 3 ≤ nums.length ≤ 3000  |  −10⁵ ≤ nums[i] ≤ 10⁵
Try Examples
Custom:
Approach
Sort + Fix Anchor + Two-Pointer Scan
Sort the array. Fix each element as anchor i. Run L=i+1, R=n-1 inward: sum<0→L++, sum>0→R--, sum=0→save+skip dups. Skip duplicate anchors. O(n²) time, O(1) space.
① Sort
›
② Fix Anchor
›
③ Two-Pointer Scan
›
④ Done
nums[i] —
+
nums[L] —
+
nums[R] —
=
sum ?
Sorting
Press Play to begin the animation.
Triplets Found
Variables
i (anchor)
—
L (left)
—
R (right)
—
sum
—
Step Logic
Press ▶ Play or Next Step to begin.
🎉
—
Unique triplets summing to zero
Ready 0 / 0
Select an example and press Play.
Algorithm
1
Sort the array — enables two-pointer technique
2
Fix anchor i; skip if nums[i]==nums[i-1] (duplicate)
3
Two pointers L=i+1, R=n-1; scan inward while L<R
4
sum=0 → save triplet + skip dups at L,R; sum<0 → L++; sum>0 → R--
Time
O(n²)
Space
O(1)
Why It Works

Why sort? After sorting, if sum is too small we know moving L right (to bigger values) will increase it. If sum is too large, moving R left decreases it. This eliminates guessing.

Why skip duplicates? After sorting, duplicates are adjacent. Skipping them at both anchor and pointer levels guarantees unique triplets without a HashSet.

Why O(n²)? O(n log n) sort + outer loop O(n) × inner two-pointer O(n) = O(n²) total. Each element is visited at most once per anchor.

How to solve 3Sum

LeetCode 15 · Medium · Arrays · Pattern: Sort + Two Pointers

Why the obvious approach is slow

Three nested loops check every triplet in O(n) cubed. And you would still have to remove duplicate triplets afterwards.

The key idea

First sort the array. Fix one number, then find the other two with two pointers, just like Two Sum 2. If the sum is too small, move the left pointer right, and if it is too big, move the right pointer left. Skip any value equal to the one before it, so no triplet repeats.

Remember

Sort, fix one number, two pointers for the other two. Skip equal neighbours to avoid duplicate triplets.

Run the animation above on your own input, or watch the 1:47 video explanation of 3Sum with a dry run and Java code.

More Arrays problems