Minimum Swaps to Group All 1's Together

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
  • -105 <= nums[i] <= 105

Solution

Since we have learned how to find 2 Sum given a sorted array, 3 Sum is just one more number added onto the 2 sum. We can wrap the two pointer 2 sum implementation by a for loop that chooses the first element of the 3 sum for us. Using the deduplication patterns from Deduplication, we can easily find unique triplet that sums to 0.

  • We avoid duplicate first element by checking whether nums[i] == nums[i-1] in every iteration.
  • We avoid duplicating the second element by checking whether nums[l] == nums[l-1] in the selection of the left pointer.
  • The value of the third element is based on the first and second elements, thus the triplets will be unique.

Implementation

def threeSum(self, nums: List[int]) -> List[List[int]]:
    nums.sort()
    res = []
    for i in range(len(nums)):
        if nums[i] > 0 or i > 0 and nums[i] == nums[i-1]: continue
        l, r = i+1, len(nums)-1
        while l < r:
            total = nums[i] + nums[l] + nums[r]
            if total == 0:
                res.append([nums[i], nums[l], nums[r]])
                l, r = l+1, r-1
                while l < len(nums) -1 and nums[l] == nums[l-1]:
                    l += 1
            elif total > 0:
                r -= 1
            else:
                l += 1
    return res

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator
Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

Which data structure is used to implement priority queue?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


310 gowtham sagar

the title of the question itself is wrong.

Sun Jun 23 2024
pranav kumar

I think it's to avoid plagiarism litigation

Sat Jul 20 2024