Number of Good Pairs

Problem Summary

(Write in your own words, not copied from LeetCode. This forces comprehension.)

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

(c2)=c(c1)2

good pairs.
So the total number of good pairs is

v(cv2)=vcv(cv1)2,

where cv is the count of value v.

Why it works (two easy views)

  1. Combinatorial (choose 2 indices):
    For any fixed value v with c occurrences, a “good pair” is just choosing 2 distinct indices among those c. The number of ways to choose 2 items from c is (c2). Summing over values gives the total.

  2. Ordered-to-unordered (double counting):
    Among the c equal elements, there are c(c1) ordered pairs (i,j) with ij. But each unordered pair {i,j} appears twice (once as (i,j) and once as (j,i)). Restricting to i<j divides by 2, giving c(c1)/2.

Tiny example

nums = [1,1,1,2,2,3]
Counts: c1=3,c2=2,c3=1.
Pairs = (32)+(22)+(12)=3+1+0=4.
(The pairs are (0,1), (0,2), (1,2) for 1’s, and (3,4) for 2’s.)

Notes / edges

That’s it—the (c2) piece is the whole trick.


Main Concepts Used

(Mark the CS concepts or algorithms used.)

Time & Space Complexity

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