ToolMight Logo
MediumTwo PointersArrays & HashingSort then Two PointersDuplicate SkippingTriplet Zero Sum

3Sum

Find all unique integer triplets summing to zero. Compare hash-set pair lookup against sorting + two-pointer inward scans with duplicate skipping.

Optimal Time
O(n²)
Optimal Space
O(1) to O(n)
Primary Pattern
Sort then Two Pointers
Visualizer
Open Interactive View →

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 & Constraints

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. Distinct triplets are [-1, 0, 1] and [-1, -1, 2].
Example 2
Input: nums = [0, 1, 1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Constraints
  • 3 <= nums.length <= 3000
  • -10^5 <= nums[i] <= 10^5

Pattern Recognition & Core Invariant

How to Spot This Pattern

Multi-sum target problems (3Sum, 4Sum) sort the array first to collapse nested loops into two-pointer scans and skip duplicates cleanly via adjacent comparison.

Core Invariant

After sorting ascending, fixing nums[i] reduces the search to pairs in [i+1..n-1] summing to -nums[i], and skipping adjacent equal values guarantees unique output triplets.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Sort + Two-Sum Hash Set Lookup
O(n²)O(n)After sorting to skip duplicate pivots, run a O(n) Hash Set complement lookup inside the outer loop to find pairs summing to -nums[i].
2. Sort & Two-Pointer Inward ScanOptimal
O(n²)O(1) to O(n)Sort the array first. Fix the first element with an outer loop, then use two converging pointers to find pairs that sum to the target negation in O(n²) time.

1. Sort + Two-Sum Hash Set Lookup

TimeO(n²)
SpaceO(n)

After sorting to skip duplicate pivots, run a O(n) Hash Set complement lookup inside the outer loop to find pairs summing to -nums[i].

Time ComplexityO(n²)

N outer pivots each perform an O(n) hash-set inner pass.

Space ComplexityO(n)

Allocates a Hash Set of up to n elements per outer step.

How It Works

Reducing 3Sum to Repeated Two-Sum Lookups

If you replace the two converging pointers with a Hash Set complement scan for each outer index i:

  1. Sort nums (still crucial so duplicate outer nums[i] values can be skipped cleanly).
  2. For each i with nums[i] <= 0:
  • Initialize an empty seen set.
  • Loop j from i + 1 to n - 1: compute complement = -nums[i] - nums[j].
  • If complement is in seen, emit [nums[i], complement, nums[j]] and advance j past duplicates so the pair isn't emitted twice.
  • Add nums[j] into seen.

While still O(n²) time, this allocates O(n) hash-set memory compared to Two Pointers' O(1) auxiliary work.

Step-by-Step Dry Run

Execution Trace·Step 1 of 2
1Fix Outer Pivot nums[1] = -1

Scan suffix [-1, 0, 1, 2] with seen = {}. complement for -1 is 2 (not seen yet); insert -1.

State:seen = {-1}
Strengths
  • +Connects 3Sum directly to classic 2Sum complement lookup
Trade-offs
  • -Uses O(n) hash-set heap allocations per outer loop; slower constant factors than Two Pointers

Reference Implementation

Complete implementation for Sort + Two-Sum Hash Set Lookup in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def three_sum_hash(nums: list[int]) -> list[list[int]]:
nums.sort()
res = []
n = len(nums)
for i in range(n - 2):
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
seen = set()
j = i + 1
while j < n:
comp = -nums[i] - nums[j]
if comp in seen:
res.append([nums[i], comp, nums[j]])
while j + 1 < n and nums[j] == nums[j + 1]:
j += 1
seen.add(nums[j])
j += 1
return res

2. Sort & Two-Pointer Inward Scan

Optimal
TimeO(n²)
SpaceO(1) to O(n)

Sort the array first. Fix the first element with an outer loop, then use two converging pointers to find pairs that sum to the target negation in O(n²) time.

Time ComplexityO(n²)

Sorting takes O(n log n). The outer loop runs N times, and each two-pointer inner scan takes O(n). Total runtime is O(n log n + n²) = O(n²).

Space ComplexityO(1) to O(n)

O(1) auxiliary space beyond the output array if in-place sorting is used, or O(n) for the sorting stack frames depending on language implementation.

How It Works

Why Naive Brute Force Is Prohibitive

An exhaustive three-loop search evaluates all combinations in O(n³) time. For N = 3,000, 3000³ is 27,000,000,000 operations, which guarantees a timeout.

The Two-Pointer Reduction

If we sort the array first (O(n log n)), we can reduce the 3-variable problem into a sequence of sorted 2-variable problems:

  1. Sort `nums` in ascending order.
  2. Iterate i from 0 to n - 3:
  • Pruning: If nums[i] > 0, terminate the outer loop immediately! Since the array is sorted, any subsequent positive numbers can never sum to zero.
  • Skip Outer Duplicates: If i > 0 and nums[i] == nums[i - 1], skip to prevent duplicate triplets.
  • Set left = i + 1 and right = n - 1.
  1. While left < right:
  • Calculate sum = nums[i] + nums[left] + nums[right].
  • If `sum == 0`: We found a valid triplet! Record [nums[i], nums[left], nums[right]].
  • Advance left++ while skipping any identical consecutive values (nums[left] == nums[left - 1]).
  • Decrement right-- while skipping any identical consecutive values (nums[right] == nums[right + 1]).
  • If `sum < 0`: The sum is too small. Advance left++ to increase value.
  • If `sum > 0`: The sum is too large. Decrement right-- to decrease value.

Handling Duplicates Without Extra Sets

The genius of sorting first is that duplicate numbers are clustered together. By explicitly skipping identical numbers at both the outer pivot i and the inner pointers (left and right), we guarantee zero duplicate triplets without wasting memory on an auxiliary hash set.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1Sort Array

[-1, 0, 1, 2, -1, -4] sorted becomes [-4, -1, -1, 0, 1, 2].

State:nums = [-4, -1, -1, 0, 1, 2]
Strengths
  • +Optimal O(n²) runtime
  • +Zero memory waste by skipping duplicate values in-place
Trade-offs
  • -Mutates original array ordering (requires sorting)

Reference Implementation

Complete implementation for Sort & Two-Pointer Inward Scan in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def three_sum(nums: list[int]) -> list[list[int]]:
nums.sort()
res = []
n = len(nums)
for i in range(n - 2):
if nums[i] > 0:
break
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
res.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return res
if __name__ == "__main__":
nums = [-1, 0, 1, 2, -1, -4]
print("Unique Triplets:", three_sum(nums))
Interactive Visualizer

Trace Array & Matrix mechanics in memory

Step through custom inputs in the Array & Matrix visualizer to inspect pointer updates, array shifts, and call-stack state alongside 3Sum.

Open Array & Matrix visualizer

Frequently Asked Questions

Why break at `nums[i] > 0` instead of `nums[i] >= 0`?

If nums[i] == 0, [0, 0, 0] is still a valid zero-sum triplet! Only when the smallest element nums[i] is strictly positive (> 0) are all subsequent elements positive, making a zero sum impossible.

How do we prevent duplicate triplets from appearing in the output?

After sorting, adjacent elements are equal whenever duplicates exist. Skipping nums[i] == nums[i - 1] on the outer loop and skipping identical values on left and right after each match eliminates duplicates in-place.

Why is `O(n²)` the practical target rather than `O(n log n)`?

A length-N array can contain up to O(n²) distinct valid zero-sum triplets in the worst case, so even outputting all answers requires quadratic lower-bound time.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • All zeroes ([0, 0, 0, 0]) must output [[0, 0, 0]] once without pruning on nums[i] >= 0.
  • Repeated duplicates like [-2, 0, 0, 2, 2] require skipping duplicates on both left and right pointers after recording [-2, 0, 2].
  • All-positive ([1, 2, 3]) or no-solution arrays return [].

Common Bugs to Avoid

  • Pruning with `if (nums[i] >= 0) break;` instead of `>` — which skips `[0, 0, 0]` when all elements are 0!
  • Forgetting to skip duplicates on BOTH the outer index `i` and inner `left`/`right` after recording a triplet.
  • Sorting output triplets inside a hash set slowly in O(n³) or O(n²) extra memory when two pointers deduplicate in-place.

Interview Follow-Up Variations

  • 3Sum Closest: minimize `abs(sum - target)` using the identical sort + two-pointer scan.
  • 4Sum and general kSum: recursively fix one element down to the k == 2 sorted two-pointer base case.

Related Problems

All problems
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve
EasyTwo Pointers

Valid Palindrome

Check whether a string reads identically forward and backward over alphanumeric characters. Compare build-and-reverse against O(1)-space converging pointers.

Pattern: Two Pointers Converging
O(n) · O(1)
Solve
EasyArrays & Hashing

Contains Duplicate

Check whether any integer repeats inside an array. Compare early-exit O(n) Hash Set membership testing against O(1)-space in-place sorting.

Pattern: Hash Set
O(n) · O(n)
Solve