MediumNo. 1814
Count Nice Pairs in an Array — LeetCode 1814 Python Solution
- Pattern
- Math and Number Theory
- Topics
- Array, Hash Table, Math, Counting
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x.
Example
- Input
- nums = [42,11,1,97]
- Output
- 2
- Explanation
- The two pairs are:
Python solution
class Solution:
def countNicePairs(self, nums: List[int]) -> int:
def rev(x):
y = 0
while x:
y = y * 10 + x % 10
x //= 10
return y
cnt = Counter(x - rev(x) for x in nums)
mod = 10**9 + 7
return sum(v * (v - 1) // 2 for v in cnt.values()) % modComplexity
- Time
- O(n × log M)where n and M are the length of the nums array and the maximum value in the nums array, respectively
- Space · auxiliary
- O(n)
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1814. Count Nice Pairs in an Array 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 |
| 1512 | Number of Good Pairs | Easy |
| 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 1814. Count Nice Pairs in an Array?
LeetCode 1814. Count Nice Pairs in an Array is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1814. Count Nice Pairs in an Array?
The Python solution on this page runs in O(n × log M), where n and M are the length of the nums array and the maximum value in the nums array, respectively.
- What is the space complexity of LeetCode 1814. Count Nice Pairs in an Array?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1814. Count Nice Pairs in an Array cover?
LeetCode 1814. Count Nice Pairs in an Array is tagged Array, Hash Table, Math and Counting on LeetCode.