DSA problem
Number of Good Pairs
Given an array of integers nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
In other words, you must count every unordered pair of distinct indices whose values are equal. A brute-force scan over all index pairs works but is quadratic; using a hash map of value frequencies lets you count the pairs in a single pass. For each value, if it appears c times, it contributes c * (c - 1) / 2 good pairs.
Examples
Example 1
Input:
nums = [1,2,3,1,1,3]Output:
4Explanation: There are 4 good pairs (0,3), (0,4), (3,4) at value 1 and (2,5) at value 3, all 0-indexed.
Example 2
Input:
nums = [1,1,1,1]Output:
6Explanation: Each pair of the four equal elements is good: C(4,2) = 6 pairs in total.
Example 3
Input:
nums = [1,2,3]Output:
0Explanation: All values are distinct, so no pair satisfies nums[i] == nums[j].
Constraints
- 1 <= nums.length <= 100
- 1 <= nums[i] <= 100
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.