Count Nice Pairs in an Array — LeetCode 1814 Python Solution

MediumArrayHash TableMathCounting
Problem
#1814
Reading time
2 min

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()) % mod

Complexity

MeasureComplexity
TimeO(n \times \log M), where n and M are the length of the nums array and the maximum value in the nums array, respectively
SpaceO(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

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.

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