Number of Good Pairs
Given an array of integers, count the number of good pairs. A pair (i, j) is good if nums[i] == nums[j] and i < j. The order matters — each valid pair is counted separately based on its indices, not the values.
A brute force double loop would check every possible pair in O(n²) time. A hash map approach reduces this to O(n): count how many times each number occurs, then for each frequency, the number of pairs is n * (n - 1) / 2. This formula counts all combinations of two indices among the n occurrences of the same value.
The hash map collects frequencies in one pass. Then a second pass over the map sums up the pair counts. For example, if a number appears 4 times, there are 4 * 3 / 2 = 6 good pairs for that number. This works because each pair is defined by picking any two distinct indices, and the condition i < j is automatically satisfied by exactly half of the ordered pairs.
Edge cases include an empty array (return 0), an array with all distinct values (return 0), and an array with all identical values (return n * (n-1) / 2).
The combination formula n * (n-1) / 2 comes from choosing 2 positions out of n. Since order does not matter for indices (i < j is automatic when picking distinct indices), each unordered pair of equal-valued positions forms exactly one good pair. This formula avoids nested loops entirely.
Example Input & Output
Four 1s: 4*3/2 = 6 pairs.
Three 5s: 3*2/2 = 3 pairs.
Pairs: (0,3),(0,4),(3,4) for 1; (2,5) for 3.
All distinct values, no pairs.
Empty array has no pairs.
Algorithm Flow

Solution Approach
Count frequencies with a hash map. Sum n * (n-1) / 2 for each frequency n.
Time O(n), Space O(n).
Best Answers
import java.util.*;
class Solution {
public int solution(int[] nums) {
Map<Integer,Integer> freq = new HashMap<>();
for (int n : nums) freq.put(n, freq.getOrDefault(n, 0) + 1);
int total = 0;
for (int n : freq.values()) total += n * (n - 1) / 2;
return total;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
