Skip to content

15. 3Sum

MediumLeetCode

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.

Example 1:

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.

Example 2:

Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0.

Example 3:

Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0.

Constraints:

  • 3 <= nums.length <= 3000
  • -10<sup>5</sup> <= nums[i] <= 10<sup>5</sup>

How to solve the problem

  • Sorting the array nums first if we want to use two pointer approach.

  • Once we find a triplet we need, we have to do j++ and k-- in the mean time to find another one. And using nums[j] == nums[j-1]and nums[k] == nums[k+1] to make sure there is no duplicate triplet. while j < k is essential because we have already done j++ and k--.

  • Using ans.append([nums[i], nums[j], nums[k]]) return all the triplets as an element instead of adding any single element into ans.

Code

python
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        ans = []
        for i in range(len(nums) - 2):
            j = i + 1
            k = len(nums) - 1
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            while j < k:
                s = nums[i] + nums[j] + nums[k]
                if s < 0:
                    j += 1
                elif s > 0:
                    k -= 1
                else:
                    ans.append([nums[i], nums[j], nums[k]])
                    j += 1
                    k -= 1
                    while j < k and nums[j] == nums[j - 1]:
                        j += 1
                    while j < k and nums[k] == nums[k + 1]:
                        k -= 1
        return ans

Complexity

Time complexity: O(n²)

  • Traversing nums[i] is O(n), two pointer is O(n), so in total is O(n²).

Space complexity: O(1)

  • We ignore the memory required for the output. For the purpose of complexity analysis, we also ignore sorting algorithm.

Comments

No comments yet. Be the first to comment!