CodeArchon

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
2
0
3
1
4
2
5
1/20
Narrationstep 1 of 20

Sort the input first: [-4, -1, -1, 0, 1, 2]. Sorting lets us use two pointers for each anchor.

1def zero_sum_trios(nums: list[int]) -> list[list[int]]:
2 a = sorted(nums)
3 out = []
4 for i in range(len(a) - 2):
5 if i > 0 and a[i] == a[i - 1]:
6 continue
7 lo, hi = i + 1, len(a) - 1
8 while lo < hi:
9 s = a[i] + a[lo] + a[hi]
10 if s == 0:
11 out.append([a[i], a[lo], a[hi]])
12 while lo < hi and a[lo] == a[lo + 1]:
13 lo += 1
14 while lo < hi and a[hi] == a[hi - 1]:
15 hi -= 1
16 lo += 1; hi -= 1
17 elif s < 0:
18 lo += 1
19 else:
20 hi -= 1
21 return out
Variables
phase=sort

How to think about it

  1. Brute force is O(n³). Sorting unlocks two pointers → O(n²).
  2. Fix anchor i. Use lo/hi on the suffix to find pairs with target = -nums[i].
  3. If sum == 0, record; then step past duplicates on both sides.
  4. If sum < 0, nudge lo right; otherwise nudge hi left.
  5. 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