Problem 816
Number of Good Pairs
Easy · 10 pts · Array, Hash Table, Counting
Problem
A pair of positions i < j is good if A[i] equals A[j]. Count the good pairs. Checking every pair is O(N²). Instead count how often each value appears: a value appearing c times contributes c × (c - 1) / 2 pairs, or equivalently, each element pairs with all equal elements seen before it. The answer can exceed 2^31.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].
Output
Print the number of good pairs.
Constraints
1 <= N <= 100000; 1 <= A[i] <= 10^9
Example input
6 1 2 3 1 1 3
Example output
4
Explanation
In 1 2 3 1 1 3, the value 1 appears three times (3 pairs) and 3 appears twice (1 pair), so there are 4 good pairs.