Skills101
← All coding problems

3Sum

mediumTwo Pointers+20 XPTime limit 4s

Find all unique triplets of values (a, b, c), taken from three different positions of the array, with a + b + c = 0.

Input:

  • line 1: n
  • line 2: n integers

Output:

  • line 1: the number of unique triplets t
  • next t lines: one triplet each, written in increasing order (a ≤ b ≤ c); list the triplets in increasing order (compare a, then b, then c)

Constraints: 3 ≤ n ≤ 3000, −10⁶ ≤ value ≤ 10⁶.

Think about it: sort, fix the first value, then find pairs with two pointers — O(n²). Skipping equal neighbours avoids duplicate triplets.

Sample input 1

6
-1 0 1 2 -1 -4

Sample output 1

2
-1 -1 2
-1 0 1

Sample input 2

3
0 1 1

Sample output 2

0

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.