Count Nice Pairs in an Array — LeetCode 1814 Python Solution
MediumArrayHash TableMathCounting
- Problem
- #1814
- Pattern
- Math and Number Theory
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M), where n and M are the length of the nums array and the maximum value in the nums array, respectively |
| Space | O(n) auxiliary |
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
LeetCode 914X of a Kind in a Deck of CardsEasyLeetCode 1512Number of Good PairsEasyLeetCode 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 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 \times \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.