Sum of k-Mirror Numbers — LeetCode 2081 Python Solution

HardMathEnumeration
Problem
#2081
Reading time
4 min

The problem

A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k. For example, 9 is a 2-mirror number.

Example

Input
k = 2, n = 5
Output
25
Explanation
The 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows:

Python solution

Python
class Solution:
    def kMirror(self, k: int, n: int) -> int:
        def check(x: int, k: int) -> bool:
            s = []
            while x:
                s.append(x % k)
                x //= k
            return s == s[::-1]

        ans = 0
        for l in count(1):
            x = 10 ** ((l - 1) // 2)
            y = 10 ** ((l + 1) // 2)
            for i in range(x, y):
                v = i
                j = i if l % 2 == 0 else i // 10
                while j > 0:
                    v = v * 10 + j % 10
                    j //= 10
                if check(v, k):
                    ans += v
                    n -= 1
                    if n == 0:
                        return ans

Complexity

MeasureComplexity
TimeO(n) or O(1)
SpaceO(1), since only a constant amount of extra space is auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2081. Sum of k-Mirror Numbers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

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 2081. Sum of k-Mirror Numbers?
LeetCode 2081. Sum of k-Mirror Numbers is rated Hard on LeetCode.
What topics does LeetCode 2081. Sum of k-Mirror Numbers cover?
LeetCode 2081. Sum of k-Mirror Numbers is tagged Math and Enumeration 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