#K45292. Three Sum Zero
Three Sum Zero
Three Sum Zero
You are given an array of integers. Your task is to find all unique triplets \( (a, b, c) \) in the array such that \(a+b+c=0\). Each triplet must be sorted in non-decreasing order, and the set of triplets should be output in lexicographical order.
Note: The solution should avoid duplicate triplets. For example, in the input array [-1, 0, 1, 2, -1, -4]
, the two unique triplets to be output are [-1, -1, 2]
and [-1, 0, 1]
.
This problem is a classic example that can be solved optimally by sorting the array and using a two-pointer technique.
inputFormat
The first line of input contains an integer \(T\) denoting the number of test cases. Each test case is described as follows:
- The first line contains an integer \(N\) — the size of the array.
- The second line contains \(N\) space-separated integers representing the array.
All input is provided via stdin
.
outputFormat
For each test case, first output an integer \(K\) which is the number of unique triplets that sum to zero. Then, output \(K\) lines, each containing a valid triplet (three space-separated integers) in non-decreasing order. The triplets for each test case must be printed in lexicographical order. All output should be printed to stdout
.
2
6
-1 0 1 2 -1 -4
5
-1 -1 -1 2 -1
2
-1 -1 2
-1 0 1
1
-1 -1 2
</p>