Number of Good Pairs
Problem Summary
(Write in your own words, not copied from LeetCode. This forces comprehension.)
- Given a list of numbers, return number of pairs that aren't the same index and index of
jfrom(i, j)isj > i
Why This Works
(Explain the core reason the solution is correct.)
Here’s the clean math behind LeetCode 1512: Number of Good Pairs.
The formula
If a value appears c times in the array, it contributes
good pairs.
So the total number of good pairs is
where
Why it works (two easy views)
-
Combinatorial (choose 2 indices):
For any fixed valuewith occurrences, a “good pair” is just choosing 2 distinct indices among those . The number of ways to choose 2 items from is . Summing over values gives the total. -
Ordered-to-unordered (double counting):
Among theequal elements, there are ordered pairs with . But each unordered pair appears twice (once as and once as ). Restricting to divides by 2, giving .
Tiny example
nums = [1,1,1,2,2,3]
Counts:
Pairs =
(The pairs are (0,1), (0,2), (1,2) for 1’s, and (3,4) for 2’s.)
Notes / edges
- If
, (no pair possible). - Implementation-wise: count frequencies with a hash map, then sum
over all counts. Time , space up to number of distinct values.
That’s it—the
Main Concepts Used
(Mark the CS concepts or algorithms used.)
Time & Space Complexity
- Time:
→ Reason: - Space:
→ Reason:
Intuitive Code
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
hashmap = {}
for i, num in enumerate(nums):
hashmap[num] = hashmap.get(num, [])
hashmap[num].append(i)
result = 0
for indices in hashmap.values():
if len(indices) < 2:
continue
for i, index in enumerate(indices):
result += len(indices) - i - 1
return result
Optimized Code
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
hashmap = {}
for i, num in enumerate(nums):
hashmap[num] = hashmap.get(num, 0) + 1
result = 0
for num in hashmap.keys():
count = hashmap[num]
goodPairs = (count * (count - 1)) // 2
result += goodPairs
return result
Common Mistakes / Things I Got Stuck On
- Not using integer division
- Iterating over
numsagain which has duplicates