Zero-Sum Triplets in an Array
Arrays & HashingAuto-graded · 23 test casesLast updated
Tests two-pointer technique on sorted arrays, duplicate avoidance, and quadratic complexity optimization for finding triplet combinations.
Problem
Write a function that accepts an array of integers and returns every distinct triplet of values from the array that sums to zero.
Each triplet should contain three values from three different positions in the input array. The output must not contain duplicate triplets—if two triplets contain the same three values, include only one of them.
You may return the triplets in any order, and each triplet's values may appear in any order.
Input
numbers: a list of integers
Output
- A list of lists, where each inner list contains exactly three integers whose sum equals zero
- No two triplets in the output should contain the same set of three values
Constraints
0 ≤ len(numbers) ≤ 3000-100000 ≤ numbers[i] ≤ 100000
Examples
Example 1
Input: find_zero_sum_triplets([-1, 0, 1, 2, -1, -4])
Output: [[-1, -1, 2], [-1, 0, 1]]
Hints
Hint 1
Sorting the array first allows you to efficiently search for pairs that complement a fixed anchor value.
Hint 2
Once sorted, use two pointers moving from opposite ends to find pairs that sum to a target in linear time.
Hint 3
Skip over consecutive duplicate values during iteration to prevent generating the same triplet multiple times.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The naive approach of checking every possible triplet runs in O(n³) time, which is too slow for arrays with thousands of elements. We can reduce this to O(n²) by sorting the array first and using the two-pointer technique.
Main Strategy:
-
Sort the input array. This enables efficient pair searching and automatic duplicate handling.
-
Fix one element as an anchor and search for two other elements that sum to its negation. Loop through each element as the anchor, treating it as the first element of a potential triplet.
-
Use two pointers to find pairs in the remaining portion of the sorted array. Initialize one pointer just after the anchor and another at the end of the array. Move the pointers inward based on whether the current sum is too small or too large.
-
Skip duplicate values during iteration to ensure each unique triplet is only added once. After processing an anchor value, skip any subsequent elements with the same value. Similarly, after finding a valid triplet, skip duplicate values on both the left and right pointers.
-
Early termination: If the anchor value is positive, all subsequent values are also positive (since the array is sorted), making a zero sum impossible. Stop the search early in this case.
Why This Works:
The sorting step groups duplicate values together, making it straightforward to skip them during iteration. For a fixed anchor value, the two-pointer approach efficiently explores all valid pairs in linear time by exploiting the sorted order. When the sum is too small, only moving the left pointer can increase it; when too large, only moving the right pointer can decrease it. This guarantees we examine every potential triplet exactly once without missing any valid combinations.
By skipping duplicate anchors and duplicate pointer values immediately after finding a match, we ensure that each unique set of three values appears in the output only once, without needing additional data structures for deduplication.
Complexity:
- Time: O(n²) — Sorting takes O(n log n), and for each of the n possible anchors, the two-pointer scan takes O(n) in the worst case. The dominant term is n².
- Space: O(1) auxiliary — Beyond the output list and the space used by the sorting algorithm (which may use O(n) temporary storage), we only use a constant number of variables.
Solution
from typing import List
def find_zero_sum_triplets(numbers: List[int]) -> List[List[int]]:
numbers.sort()
result = []
n = len(numbers)
for i in range(n - 2):
if i > 0 and numbers[i] == numbers[i - 1]:
continue
if numbers[i] > 0:
break
left, right = i + 1, n - 1
while left < right:
total = numbers[i] + numbers[left] + numbers[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
result.append([numbers[i], numbers[left], numbers[right]])
left += 1
right -= 1
while left < right and numbers[left] == numbers[left - 1]:
left += 1
while left < right and numbers[right] == numbers[right + 1]:
right -= 1
return result