3Sum: Unique Triplets

Problem

Print all different triplets (a, b, c) from the array with a + b + c = 0. Each triplet is printed in ascending order as a b c, and the triplets are printed in ascending order too. A triplet uses three different positions but no triplet value is printed twice. Print none if there is no triplet.

Constraints

  • 1 <= n <= 3000

Examples

Input

6
-1 0 1 2 -1 -4

Output

-1 -1 2
-1 0 1

Solutions

Best approachTime O(n^2)Space O(1) extra

Checking all triples costs O(n^3). After sorting, one fixed value and two moving pointers need only O(n^2). Skipping repeated values is what keeps the triplets unique.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array.
 * Input   : n, then n integers.
 * Output  : The triplets.
 * Approach: Sort, then two pointers.
 * Time    : O(n^2)
 * Space   : O(1) extra
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(int[] a) {
        // Step 1: Sort the array. Then we can use two pointers and skip repeated values easily.
        java.util.Arrays.sort(a);
        java.util.List<String> found = new java.util.ArrayList<>();

        for (int i = 0; i < a.length - 2; i++) {
            // Step 2: Skip a first value that is the same as the one before. It would give the same triplets.
            if (i > 0 && a[i] == a[i - 1]) {
                continue;
            }

            // Step 3: Two pointers look for a pair with the sum -a[i].
            int left = i + 1;
            int right = a.length - 1;
            while (left < right) {
                long sum = (long) a[i] + a[left] + a[right];
                if (sum < 0) {
                    left++;
                } else if (sum > 0) {
                    right--;
                } else {
                    found.add(a[i] + " " + a[left] + " " + a[right]);
                    left++;
                    right--;

                    // Step 4: Skip repeated values on the left side, so the same triplet is not printed twice.
                    while (left < right && a[left] == a[left - 1]) {
                        left++;
                    }
                }
            }
        }

        if (found.isEmpty()) {
            found.add("none");
        }
        return found.toArray(new String[0]);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(String.join("\n", solve(a)));
    }
}
Hints (1)
  1. Why do we sort first?