↓Skip to main content
  1. LeetCode/

LeetCode 1512: Number of Good Pairs

·1 min· ·
LeetCode Easy Math Hash-Table Counting Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2025-12-18

  • Submissions: Accepted ×2 (Python) → Compile Error → Accepted ×2 (C++)

Approach
#

Count pairs with nums[i] == nums[j] and i < j.

  • Brute force: a double loop, O(n^2), fine for n <= 100.
  • Counting: a value appearing c times gives c × (c - 1) / 2 pairs.
  • Count while scanning: on reading x, it pairs with every earlier x, so add cnt[x] to the answer and then increment cnt[x].

My Solution
#

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        cnt = Counter()
        pairs = 0
        for x in nums:
            pairs += cnt[x]                        # pair with every earlier x
            cnt[x] += 1
        return pairs

I first wrote the brute force and the combination formula in Python, then practiced the scanning version in C++; that Compile Error was a missing semicolon after return res.

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • The combination with / yields a float; use //, or just count while scanning.

Interview Explanation
#

I count while scanning: each number pairs with every earlier equal number, so I add how many times it has appeared so far, then increment that count. Time O(n).

Related

LeetCode 914: X of a Kind in a Deck of Cards
·2 mins
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 note: every card count must be divisible by one X >= 2, i.e. the GCD of all counts is at least 2
LeetCode 3712: Sum of Elements With Frequency Divisible by K
·1 min
LeetCode Easy Hash-Table Counting Array
LeetCode 3712 note: count each value, and for counts divisible by k add value × count
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 min
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 note: a word is formable when none of its character counts exceeds chars’; sum the lengths of such words
LeetCode 1814: Count Nice Pairs in an Array
·1 min
LeetCode Medium Array Hash-Table Math Counting
LeetCode 1814 note: rearrange the condition into nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]), count pairs per value, and remember the modulus
LeetCode 1128: Number of Equivalent Domino Pairs
·2 mins
LeetCode Easy Array Hash-Table Counting
LeetCode 1128 note: normalize each domino to (small, large) as a key and count; a key with c dominoes yields c(c - 1) / 2 pairs
LeetCode 819: Most Common Word
·2 mins
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 note: replace punctuation with spaces, lowercase, split, count, and pick the most frequent word not banned