62. Three Sum

MediumArrayArray

Given an integer array nums, return all the 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.

Input: An integer array nums.

Output: List of unique triplets that sum to zero, each sorted in non-decreasing order.

Examples

Example 1
Input: [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: Sort: [-4,-1,-1,0,1,2].
i=0(-4): l=1(-1),r=5(2): -4-1+2=-3<0→l++. l=2(-1),r=5(2): -4-1+2=-3<0→l++. l=3(0),r=5(2): -4+0+2=-2<0→l++. l=4(1),r=5(2): -4+1+2=-1<0→l++. l>=r stop.
i=1(-1): l=2(-1),r=5(2): -1-1+2=0→add[-1,-1,2]. Skip dupes. l=3,r=4: -1+0+1=0→add[-1,0,1].
Result: [[-1,-1,2],[-1,0,1]].
Example 2
Input: [0,1,1]
Output: []
Explanation: No triplet sums to 0.
Example 3
Input: [0,0,0]
Output: [[0,0,0]]
Explanation: Only one unique triplet: [0,0,0].

Constraints

Asked by

AdobeBloombergAmazonMicrosoftGoogleMeta
Solve this problem in the editor →