Asked at
3Sum
MediumVerifiedArrayTwo PointersSorting~25 min
Given an integer array nums, return all unique triplets [a, b, c] that sum to 0, using three distinct positions. The solution set must contain no duplicate triplets.
Sort, fix one element, then two-pointer the rest while skipping equal values to avoid duplicates. The input arrives as a single array nums.
Examples
in[-1, 0, 1, 2, -1, -4]
out[[-1, -1, 2], [-1, 0, 1]]
Both triplets sum to 0 and use distinct positions; no duplicates.
in[0, 1, 1]
out[]
No three values sum to 0.
Constraints
- 3 ≤ nums.length ≤ 3000
- -10⁵ ≤ nums[i] ≤ 10⁵
- The triplets and their order may be returned in any order.
Get help
🔑
Sign in to solve
Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.