All problems

Problem 99

Three Sum Count

Medium · 20 pts · Array, Two Pointers, Sorting

Problem

You are given an array of N integers. Count the distinct triplets of values (a, b, c) that add up to 0, where the three values come from three different positions of the array. Triplets with the same values in any order count only once, so (-1, 0, 1) and (0, 1, -1) are the same triplet. Sort the array. For each first element (skipping repeated values), use two pointers on the rest to find pairs that sum to minus that element, skipping duplicates as you move the pointers. This runs in O(N²).

Input

First line: integer N. Second line: N space-separated integers.

Output

Print the number of distinct zero-sum triplets.

Constraints

3 <= N <= 3000; -100000 <= A[i] <= 100000

Example input

6
-1 0 1 2 -1 -4

Example output

2

Explanation

In -1 0 1 2 -1 -4, the zero-sum triplets are (-1, -1, 2), using both -1's, and (-1, 0, 1). Any other combination is a repeat of one of these, so the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Squares of a Sorted Array Next: Pair With Given Difference