Identify Unique Zero-Sum Triples
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Find all distinct combinations of three elements in an integer sequence that sum to zero using two pointers and duplicate handling.
Given an array of integers a, identify all unique groups of three elements whose sum equals 0.
Each triple must consist of values from three distinct indices in a. If duplicate numbers appear in different positions, they may be combined, but the output must contain no duplicate value triples.
Rules & Formatting
- Each individual triple must be sorted in non-decreasing order: $[x, y, z]$ where $x \le y \le z$.
- The output list of triples must be sorted in lexicographical order.
- If no valid triples exist, return an empty list
[].
Constraints
0 <= len(a) <= 3000-1000000 <= a[i] <= 1000000
Examples
Example 1
Input: find_zero_sum_triplets([-1, 0, 1, 2, -1, -4])
Output: [[-1, -1, 2], [-1, 0, 1]]
Example 2
Input: find_zero_sum_triplets([0, 0, 0, 0])
Output: [[0, 0, 0]]
Example 3
Input: find_zero_sum_triplets([])
Output: []
Example 4
Input: find_zero_sum_triplets([-2, 0, 1, 1, 2])
Output: [[-2, 0, 2], [-2, 1, 1]]
Hints
Hint 1
Sorting the array beforehand allows you to iterate through the first element and solve the remaining subproblem using two pointers.
Hint 2
To avoid returning identical triples, skip duplicate values for the first element as well as subsequent pointers after a match is found.
Hint 3
If the fixed first element is strictly greater than 0 in a sorted array, can any three elements sum to zero?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The problem asks for every unique combination of three array elements that sum to zero. A brute-force approach testing all triplets would take $O(n^3)$ time. We can optimize this to $O(n^2)$ using a sorting and two-pointer strategy.
- Sort the Input Array: Sorting places identical numbers adjacent to one another and allows us to use pointer traversal based on numerical ordering.
- Fix the First Value: Iterate through the sorted array with an index $i$ representing the smallest element of the potential triple. If
values[i] > 0, we can terminate early because three positive numbers cannot sum to zero. - Two-Pointer Search: For a fixed $i$, set
left = i + 1andright = len(a) - 1. Compute the sumtotal = values[i] + values[left] + values[right]:- If
total == 0, record the triple[values[i], values[left], values[right]]. Advanceleftand decrementright, skipping any duplicate values for both pointers. - If
total < 0, the sum is too small; incrementleftto increase the sum. - If
total > 0, the sum is too large; decrementrightto decrease the sum.
- If
- Duplicate Prevention: Skip equal values at index $i$ (when $i > 0$ and
values[i] == values[i - 1]) and moveleft/rightpast duplicate entries whenever a match is recorded.
Complexity
- Time Complexity: $O(n^2)$. Sorting takes $O(n \log n)$. The outer loop runs $n$ times, and the inner two-pointer scan processes the remainder of the array in $O(n)$ time per iteration.
- Space Complexity: $O(n)$ auxiliary space to hold the sorted copy of the input array (or $O(1)$ extra space if sorted in place), excluding the memory required for the output list.
from typing import List
def find_zero_sum_triplets(a: List[int], k: int = 0) -> List[List[int]]:
values = sorted(a)
result = []
n = len(values)
for i in range(n - 2):
if i > 0 and values[i] == values[i - 1]:
continue
if values[i] > 0:
break
left, right = i + 1, n - 1
while left < right:
total = values[i] + values[left] + values[right]
if total == 0:
result.append([values[i], values[left], values[right]])
left += 1
right -= 1
while left < right and values[left] == values[left - 1]:
left += 1
while left < right and values[right] == values[right + 1]:
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return result