Medium
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]]
Example 2:
Input: nums = []
Output: []
Example 3:
Input: nums = [0]
Output: []
Constraints:
0 <= nums.length <= 3000-105 <= nums[i] <= 105Here are the steps to solve the “3Sum” problem:
nums in ascending order.result to store the triplets.nums from index i = 0 to i = len(nums) - 3.left and right) to find a pair of elements whose sum is equal to the negation of the current element (-nums[i]).
left = i + 1 and right = len(nums) - 1.nums[i] + nums[left] + nums[right] == 0.left.right.[nums[i], nums[left], nums[right]] to the result list.class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
# Sort the array
nums.sort()
result = []
# Iterate through the array
for i in range(len(nums) - 2):
# Check for duplicate elements
if i > 0 and nums[i] == nums[i - 1]:
continue
# Two pointers for 2Sum
left, right = i + 1, len(nums) - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
# Add triplet to result
result.append([nums[i], nums[left], nums[right]])
# Skip duplicate elements
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
# Move pointers
left += 1
right -= 1
return result
# Example Usage:
solution = Solution()
# Example 1:
nums1 = [-1, 0, 1, 2, -1, -4]
print(solution.threeSum(nums1)) # Output: [[-1, -1, 2], [-1, 0, 1]]
# Example 2:
nums2 = []
print(solution.threeSum(nums2)) # Output: []
# Example 3:
nums3 = [0]
print(solution.threeSum(nums3)) # Output: []
This code defines a Solution class with a method threeSum that takes an array nums as input and returns a list of unique triplets whose sum is equal to zero. The example usage demonstrates how to create an instance of the Solution class and call the threeSum method with different inputs.