Number of Good Pairs — LeetCode 1512 Python Solution

EasyArrayHash TableMathCounting
Problem
#1512
Reading time
2 min

The problem

Given an array of integers nums, return the number of good pairs. A pair (i, j) is called good if nums[i] == nums[j] and i < j.

Example

Input
nums = [1,2,3,1,1,3]
Output
4
Explanation
There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.

Python solution

Python
class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        ans = 0
        cnt = Counter()
        for x in nums:
            ans += cnt[x]
            cnt[x] += 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(C) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1512. Number of Good Pairs is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1512. Number of Good Pairs?
LeetCode 1512. Number of Good Pairs is rated Easy on LeetCode.
What is the time complexity of LeetCode 1512. Number of Good Pairs?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1512. Number of Good Pairs?
The Python solution on this page uses O(C) auxiliary space.
What topics does LeetCode 1512. Number of Good Pairs cover?
LeetCode 1512. Number of Good Pairs is tagged Array, Hash Table, Math and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview