3Sum
1 approach, code in every language
Problem description
Given an integer array, find every group of three distinct positions whose values add up to zero. Each valid group is reported as a triplet of the actual numbers.
The collection you return must not contain the same triplet more than once, even if it can be formed from different index combinations. The order of the triplets in the output does not matter.
Example 1
Input: nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
Both triplets sum to zero, and duplicate arrangements of the same values are filtered out.
Example 2
Input: nums = [0, 0, 0, 0]
Output: [[0, 0, 0]]
The only combination adds to zero and is listed a single time despite the repeated zeros.
Constraints
3 ≤ nums.length ≤ 3 * 10^3-10^5 ≤ nums[i] ≤ 10^5
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Charge Neutral Triples is our own problem on the technique behind 3Sum: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free