Number of Good Pairs - Problem
Given an array of integers nums, your task is to count the number of "good pairs" in the array.
A pair (i, j) is considered good if:
nums[i] == nums[j](the values are equal)i < j(the first index comes before the second)
For example, in the array [1,2,3,1,1,3], we have:
- Indices 0 and 3:
nums[0] = nums[3] = 1✓ - Indices 0 and 4:
nums[0] = nums[4] = 1✓ - Indices 3 and 4:
nums[3] = nums[4] = 1✓ - Indices 2 and 5:
nums[2] = nums[5] = 3✓
That's 4 good pairs total!
Your goal: Return the total count of good pairs in the given array.
Input & Output
example_1.py — Python
$
Input:
[1,2,3,1,1,3]
›
Output:
4
💡 Note:
There are 4 good pairs: (0,3), (0,4), (3,4), (2,5). Each pair satisfies nums[i] == nums[j] and i < j.
example_2.py — Python
$
Input:
[1,1,1,1]
›
Output:
6
💡 Note:
All pairs are good pairs: (0,1), (0,2), (0,3), (1,2), (1,3), (2,3). With 4 identical elements, we get 4×3/2 = 6 pairs.
example_3.py — Python
$
Input:
[1,2,3]
›
Output:
0
💡 Note:
No two elements are equal, so there are no good pairs.
Visualization
Tap to expand
Understanding the Visualization
1
Start Fresh
Begin with an empty frequency counter and pairs count of 0
2
Process Each Element
For each element, add its current frequency to pairs count, then increment frequency
3
Count Incrementally
This works because the nth occurrence of a value can pair with all n-1 previous occurrences
Key Takeaway
🎯 Key Insight: Instead of comparing all pairs, we count incrementally. Each element can only pair with identical elements we've seen before, making the solution both elegant and efficient.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, with O(1) hash map operations on average
✓ Linear Growth
Space Complexity
O(n)
Hash map stores at most n entries in worst case (all elements unique)
⚡ Linearithmic Space
Constraints
- 1 ≤ nums.length ≤ 100
- 1 ≤ nums[i] ≤ 100
- The array contains only positive integers
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code