- Published on
leetcode-15 3Sum
- Authors

- Name
- Gene Zhang
Key Concept: Sort + Two Pointers - Fix one element and use two pointers to find pairs that sum to the negative of the fixed element. Sorting helps avoid duplicates and enables two-pointer technique.
Duplicate Handling: Skip duplicate values for the fixed element and when moving pointers to ensure unique triplets.
# Given an integer array nums, return all triplets [nums[i], nums[j], nums[k]]
# such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
# 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 = [0,1,1]
# Output: []
#
# Example 3:
# Input: nums = [0,0,0]
# Output: [[0,0,0]]
#
# Constraints:
# 3 <= nums.length <= 3000
# -10^5 <= nums[i] <= 10^5
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort() # Sort to enable two-pointer and handle duplicates
result = []
n = len(nums)
for i in range(n - 2):
# Skip duplicate values for first element
if i > 0 and nums[i] == nums[i - 1]:
continue
# If smallest value is positive, no solution possible
if nums[i] > 0:
break
# Two pointer approach for remaining elements
left, right = i + 1, n - 1
target = -nums[i]
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == target:
result.append([nums[i], nums[left], nums[right]])
# Skip duplicates for second element
while left < right and nums[left] == nums[left + 1]:
left += 1
# Skip duplicates for third element
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
elif current_sum < target:
left += 1
else:
right -= 1
return result
# Time Complexity: O(n^2) - O(n log n) for sort + O(n^2) for two nested loops
# Space Complexity: O(1) or O(n) depending on sorting implementation