Number of Good Pairs — LeetCode 1512 Python Solution
EasyArrayHash TableMathCounting
- Problem
- #1512
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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
LeetCode 914X of a Kind in a Deck of CardsEasyLeetCode 1814Count Nice Pairs in an ArrayMediumLeetCode 1994The Number of Good SubsetsHardLeetCode 2001Number of Pairs of Interchangeable RectanglesMediumLeetCode 2364Count Number of Bad PairsMediumLeetCode 2442Count Number of Distinct Integers After Reverse OperationsMedium
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.