Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2081: Sum of k-Mirror Numbers

In this guide, we solve Leetcode #2081 Sum of k-Mirror Numbers in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Math, Enumeration

Intuition

There is a mathematical invariant or formula that directly leads to the result.

Using math avoids unnecessary loops and reduces complexity.

Approach

Derive the formula or update rule, then compute the answer directly.

Handle edge cases like overflow or zero carefully.

Steps:

  • Identify the math relationship.
  • Compute the result with a loop or formula.
  • Handle edge cases.

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: base-10 base-2 1 1 3 11 5 101 7 111 9 1001 Their sum = 1 + 3 + 5 + 7 + 9 = 25.

Python Solution

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

The time complexity is O(n) or O(1). The space complexity is O(1)O(1)O(1), since only a constant amount of extra space is.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy