Find all different triplets of numbers in a list that add up to zero.
What to build
A program that prints every unique triplet a, b, c with a + b + c equal to 0.
Requirements
- Write each triplet in non-decreasing order, and list each different triplet once.
- Print the triplets in lexicographic order, one per line, or
none.
Input
The first line has n. The second line has the n integers.
Output
The triplets, one per line with numbers separated by spaces, or none.
Constraints
3 ≤ n ≤ 300; numbers between -10⁵ and 10⁵.
Example
Input:
6
-1 0 1 2 -1 -4
Output:
-1 -1 2
-1 0 1
Why it works
After sorting, fixing the first number turns the rest into a sorted pair-sum problem that two pointers solve in O(n). Moving past equal values prevents duplicate triplets, and sorting makes the output order lexicographic.
Examples
6 -1 0 1 2 -1 -4
-1 -1 2 -1 0 1
3 0 0 0
0 0 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Sort the list. Fix the first number, then use two pointers on the rest, like pair sum on a sorted list.
Hint 2
Skip repeated values for the first number and, after a hit, for the two pointers, so each triplet appears once.
Hint 3
The sort costs O(n log n) and the scanning O(n²), better than three nested loops.
Solution
Show one correct solution (try it yourself first)
n = int(input())
nums = sorted(map(int, input().split()))
found = []
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
lo, hi = i + 1, n - 1
while lo < hi:
s = nums[i] + nums[lo] + nums[hi]
if s < 0:
lo += 1
elif s > 0:
hi -= 1
else:
found.append((nums[i], nums[lo], nums[hi]))
lo += 1
hi -= 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1
if not found:
print("none")
for t in found:
print(*t)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step