Dry run

nums = [-1, 0, 1, 2, -1, -4]Step 1 of 13
-4
0
-1
1
-1
2
0
3
1
4
2
5
triplets
empty

Sort first: [-4, -1, -1, 0, 1, 2]. Sorting lets us skip duplicates and use two pointers.

Pythontime O(n²) · space O(1) extra (not counting the output)
1def threeSum(nums):
2 nums = sorted(nums)
3 n = len(nums)
4 result = []
5 for i in range(n - 2):
6 if i > 0 and nums[i] == nums[i - 1]:
7 continue
8 l, r = i + 1, n - 1
9 while l < r:
10 total = nums[i] + nums[l] + nums[r]
11 if total == 0:
12 result.append([nums[i], nums[l], nums[r]])
13 l += 1
14 r -= 1
15 while l < r and nums[l] == nums[l - 1]:
16 l += 1
17 while l < r and nums[r] == nums[r + 1]:
18 r -= 1
19 elif total < 0:
20 l += 1
21 else:
22 r -= 1
23 return result
Variables
i—
l—
r—
sum—

Problem

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, j != k, and nums[i] + nums[j] + nums[k] == 0. The solution set must not contain duplicate triplets.

Examples

Input: nums = [-1,0,1,2,-1,-4]Output: [[-1,-1,2],[-1,0,1]]
Input: nums = [0,1,1]Output: []

Constraints

  • 3 ≤ nums.length ≤ 3000
  • -10⁵ ≤ nums[i] ≤ 10⁵

Intuition

Sort the array first. Then fix the smallest number of each triplet at index i and use two pointers — one just after i, one at the end — to find pairs that make the total 0, moving inward based on whether the sum is too small or too big. Sorting also makes duplicate triplets trivial to skip: just skip over repeated values at i, l and r.

Brute force → Optimal

Brute force

Three nested loops over every (i, j, k) triplet, checking the sum and de-duplicating with a set.

Time O(n³)Space O(n) for de-duplication
Optimal

Sort once (O(n log n)), then for each i run a two-pointer scan over the rest of the array (O(n)) — O(n²) overall, with no extra set needed since sorting makes duplicates adjacent.

Time O(n²)Space O(1) extra (not counting the output)

Complexity

Time O(n²)Space O(1) extra (not counting the output)

Edge cases

  • Fewer than 3 numbers: no triplet is possible, return an empty list.
  • All zeros, e.g. [0,0,0,0]: only one triplet [0,0,0] should appear, not one per combination — this is exactly what the duplicate-skipping handles.

Common mistakes

  • Forgetting to skip duplicate values at i, which produces the same triplet more than once.
  • Forgetting to skip duplicates at l and r *after* finding a match, which also produces repeated triplets.
আগের সমস্যা← Two Sum II - Input Array Is Sortedপরের সমস্যাContainer With Most Water →