Skip to main content

🟨 3Sum (#15)

šŸ“‹ Problem Statement​

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.

šŸ’” Examples​

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.

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]]

šŸ”‘ Key Insights & Approach​

Core Observation: Sort array, fix one number, use two pointers for remaining two numbers to find sum of 0.

Why Sort + Two Pointers?

  • O(n²) time complexity vs O(n³) brute force
  • Easy duplicate handling with sorted array
  • Can skip duplicates efficiently

Approaches:

  1. Brute force three loops: O(n³)
  2. Hash map: O(n²) but complex duplicate handling
  3. Sort + Two pointers: O(n²) - optimal

Pattern: "Two Pointers - Fixed + Moving" pattern for sum problems.

šŸ Solution: Python​

Approach: Sort + Two Pointers​

Time Complexity: O(n²) | Space Complexity: O(1) or O(n) depending on sort

from typing import List

class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
n = len(nums)

for i in range(n - 2):
# Skip duplicates for first number
if i > 0 and nums[i] == nums[i-1]:
continue

# Two pointers for remaining two numbers
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 number
while left < right and nums[left] == nums[left+1]:
left += 1
# Skip duplicates for third number
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

šŸ”µ Solution: Golang​

Approach: Sort + Two Pointers​

Time Complexity: O(n²) | Space Complexity: O(1)

import "sort"

func threeSum(nums []int) [][]int {
sort.Ints(nums)
result := [][]int{}
n := len(nums)

for i := 0; i < n-2; i++ {
// Skip duplicates
if i > 0 && nums[i] == nums[i-1] {
continue
}

left, right := i+1, n-1
target := -nums[i]

for left < right {
currentSum := nums[left] + nums[right]

if currentSum == target {
result = append(result, []int{nums[i], nums[left], nums[right]})

// Skip duplicates
for left < right && nums[left] == nums[left+1] {
left++
}
for left < right && nums[right] == nums[right-1] {
right--
}

left++
right--
} else if currentSum < target {
left++
} else {
right--
}
}
}

return result
}

šŸ“š References​