← Back to DSA Animator
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.