Number of Good Pairs
Easy · Arrays & Hashing · Array · Hash Table · Math · Counting
Problem
You are given an array of integers nums. A pair of indices (i, j) is good when nums[i] == nums[j] and i < j.
Return the number of good pairs.
Examples
Input: nums = [2,7,2,2,7] Output: 4
The three 2s give 3 pairs and the two 7s give 1 more.
Input: nums = [5,5,5,5] Output: 6
Four equal values give 4 · 3 / 2 = 6 pairs.
Input: nums = [1,2,3] Output: 0
All values are distinct, so no pair is good.
Constraints
- 1 <= len(nums) <= 100
- 1 <= nums[i] <= 100
Approaches
- Check every pair — time O(n²), space O(1)
Follow-up
What if the array is too large to hold the counts of every value, but it arrives sorted? Then equal values sit in runs: count each run length c and add c · (c - 1) / 2, using O(1) memory.
Related problems
Start free on Cariara · Coding problems · System design studio