LC015 - 3Sum
Last updated
Last updated
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: nums[0]
+ nums[1]
+ nums[2]
= (-1) + 0 + 1 = 0. nums[1]
+ nums[2]
+ nums[4]
= 0 + 1 + (-1) = 0. nums[0]
+ nums[3]
+ nums[4]
= (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1]
and [-1,-1,2]
. Notice that the order of the output and the order of the triplets does not matter.
Complexity is time and space.
In theory, this solution would be slower than a two pointer solution, which is in theory. However, in this approach, checking the negative and positive complement while in the worst case is , runs faster the majority of times assuming that the ratio of positive and negative values is not skewed because this solution has better constant time factor. Sorting here is effectively since we sort three elements at a time.