mediumTwo PointersAmazonMetaGoogle
Zero-Sum Trio Hunt
An inventory auditor must find every trio of ledger entries that cancel to exactly zero.
Given an integer array `nums`, return every unique triplet `[a, b, c]` with `a + b + c = 0`. No two triplets in the result should be duplicates.
Choose approach
-4
0-1
1-1
20
31
42
51/20
Narrationstep 1 of 20
Sort the input first: [-4, -1, -1, 0, 1, 2]. Sorting lets us use two pointers for each anchor.
Variables
phase=sort
How to think about it
- Brute force is O(n³). Sorting unlocks two pointers → O(n²).
- Fix anchor i. Use lo/hi on the suffix to find pairs with target = -nums[i].
- If sum == 0, record; then step past duplicates on both sides.
- If sum < 0, nudge lo right; otherwise nudge hi left.
- Skip anchor i when it duplicates the previous anchor to avoid repeated trios.
Edge cases to catch in interview
- Fewer than 3 elements → no trios possible.
- Many duplicates — the skip-logic prevents repeats.
- All positives or all negatives — no trio can sum to 0.
Examples
Example 1
[[-1,-1,2],[-1,0,1]]{"nums":[-1,0,1,2,-1,-4],"values":[-4,-1,-1,0,1,2]}
Two unique trios.
Example 2
[]{"nums":[0,1,1],"values":[0,1,1]}
No triplet sums to 0.
Example 3
[[0,0,0]]{"nums":[0,0,0],"values":[0,0,0]}
Three zeros.
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed