EasyNo. 1512
Number of Good Pairs — LeetCode 1512 Python Solution
- Pattern
- Math and Number Theory
- Topics
- Array, Hash Table, Math, Counting
- 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
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
- Time
- O(n)
- Space · auxiliary
- O(C)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0914 | X of a Kind in a Deck of Cards | Easy |
| 1814 | Count Nice Pairs in an Array | Medium |
| 1994 | The Number of Good Subsets | Hard |
| 2001 | Number of Pairs of Interchangeable Rectangles | Medium |
| 2364 | Count Number of Bad Pairs | Medium |
| 2442 | Count Number of Distinct Integers After Reverse Operations | Medium |
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.