Level Up Your Coding Skills & Crack Interviews — Save up to 50% or more on Educative.io Today! Claim Discount

Arrow
Table of contents

2081. Sum of k-Mirror Numbers

This problem shows up in interview settings because it’s a compact way to test multiple “core” skills at once. You need to be comfortable switching between number systems (base-10 vs. base-k), recognize when a brute-force scan will blow up, and design a cleaner search by enumerating only meaningful candidates (base-10 palindromes) in increasing order. On top of that, it checks your ability to implement palindrome validation efficiently, handle small but strict constraints correctly.

Problem statement

A k-mirror number is a positive integer with no leading zeros that is a palindrome in base-10 and in base-k.

For example, if k = 2, then:

  • 3 is a 2-mirror number because it reads the same forwards and backwards in both bases:
    • Base-10 representation: 3
    • Base-2 representation: 11
  • 4 is not a 2-mirror number because the base-2 representation is not symmetric:
    • Base-10 representation: 4
    • Base-2 representation: 100

Given the base k and the number n, return the sum of the n smallest k-mirror numbers.

Constraints:

  • 2 ≤ k ≤ 9
  • 1 ≤ n ≤ 30

Examples

InputOutputExplanation
3, 6287The 6 smallest 3-mirror numbers are 1, 2, 4, 8, 121, 151. (Each is a palindrome in base-10 and also in base-3; e.g., 151 in base-3 is 12121.) Sum = 287.
4, 566The 5 smallest 4-mirror numbers are 1, 2, 3, 5, 55. (Example: 55 in base-4 is 313, a palindrome.) Sum = 66.
5, 7356The 7 smallest 5-mirror numbers are 1, 2, 3, 4, 6, 88, 252. (Examples: 88 in base-5 is 323, and 252 in base-5 is 2002.) Sum = 356.
8, 155818The 15 smallest 8-mirror numbers are 1, 2, 3, 4, 5, 6, 7, 9, 121, 292, 333, 373, 414, 585, 3663. (Example: 3663 in base-8 is 7117, a palindrome.) Sum = 5818.

A naive approach

A natural first attempt is to iterate over positive integers (x=1,2,3,…) and do two checks for each number:

  • Check if x is a palindrome in base 10.
  • Convert x to base k and check if it is a palindrome there as well.

This approach is correct, but it takes a lot of work. Most numbers are not palindromes in base 10, so the algorithm spends most of its time rejecting values that will never qualify.

So, let’s think of a better solution.

Intuition for an optimal solution

The key optimization is: instead of checking every integer, we should generate only those numbers that are already palindromes in base 10.

As given in the problem statement, a k-mirror number must satisfy two conditions:

  1. It reads the same forward and backward in base 10.
  2. It also reads the same forward and backward in base k.

If we scan integers normally, the first condition eliminates most values, because base-10 palindromes are relatively rare. That means checking every integer spends a large amount of time on numbers that fail immediately.

A better strategy is to start by building base-10 palindromes directly. This way, every number we produce already meets the base-10 requirement, and the only remaining work is to convert it to base-k and check whether that representation is also a palindrome.

Optimized solution: Palindrome generation + base-k check

The algorithm generates decimal palindromes in increasing order using a simple half and mirror method.

For a chosen prefix (half\text{half}half), there are two ways to form a palindrome:

  • Odd length: Mirror half\text{half}half but skip its last digit, so the middle digit is not repeated.
  • Even length: Mirror the entire half\text{half}half.

This guarantees that every produced number is a palindrome in base 10. After that, we convert the same number to base k and check whether its base-k digits also form a palindrome. Each time the check succeeds, we add the number to the running sum and increase the count. We stop as soon as we have found n such numbers.

Because these decimal palindromes are generated in increasing order, the first n numbers that pass the base-k check are exactly the n smallest k-mirror numbers.

Step-by-step algorithm

  1. Initialize counters and the half range. Set start = 1 indicating that the first set of prefixes (half) will be 1 to 9. Set k_mirrored = 0 to count how many k-mirror numbers have been found. Set total = 0 to store the sum of the found k-mirror numbers.
  2. While k_mirrored < n, keep generating base-10 palindromes and checking them.
    1. Compute end = start * 10. This makes the current prefix range: half in [start, end).
      1. If start = 1, then half is 1..9.
      2. If start = 10, then half is 10..99.
      3. If start = 100, then half is 100..999, and so on.
  3. For each half in the current range, form palindromes in two ways: Odd-length palindrome (mode = 0) and even-length palindrome (mode = 1).
    1. Build the decimal palindrome from half. Start with pal = half.
    2. Set the part to mirror:
      1. If mode == 0 (odd), set tail = half // 10.
      2. If mode == 1 (even), set tail = half.
    3. While tail is not zero:
      1. Append the last digit of tail to pal using: pal = pal * 10 + (tail % 10).
      2. Remove the last digit of tail using: tail //= 10.
    4. Check whether the same number is also a palindrome in base k. Call the helper function isPalK(k, pal). If it returns TRUE, then:
      1. Increase the count as k_mirrored += 1.
      2. Add to the sum as total += pal.
    5. If k_mirrored reaches n, stop searching.
  4. After finishing both modes for the current range, update start = end. This moves from 1-digit prefixes to 2-digit prefixes, then 3-digit prefixes, and so on.
  5. Once k_mirrored == n, return total.

How isPalK(k, num) works?

  • Convert num into base k by repeatedly taking remainders:
    • Each step appends num % k to a list of digits. Then update num //= k to continue.
  • After conversion, check if the digit list is the same forwards and backwards:
    • Return digs == digs[::-1].

Solution code implementation in Python

Let’s look at the code of the optimal solution approach we just discussed.

Time complexity

The algorithm generates decimal palindromes and checks each one in base-k. If T palindromes are tested before finding n valid numbers, and X is the largest tested value, then the complexity becomes:

$O(T×(log⁡⁡_{10}(X)+log⁡⁡k(X))$

This reduces to constant time, O(1), under the problem constraints because n ≤ 30 and 2 ≤ k ≤ 9. These fixed limits place an upper bound on how many palindromes are tested and how large X can become, so the total work is bounded by a constant for all valid inputs.

Space complexity

The algorithm stores the base-k digits of one palindrome at a time, which requires $O(\log_{k} (X)$ space.

Can we simplify further?

Yes. Because the constraints are small and fixed, 2 ≤ k ≤ 9 and n ≤ 30, it is possible to precompute the first 30 k-mirror numbers for every base k in [2, 9]. Once those lists are precomputed, the runtime solution becomes a direct lookup followed by summation. This removes the need to generate palindromes, convert bases, or perform palindrome checks during execution.

The solution below uses a precomputed table. For each base k from 2 to 9, ANS[k-2] already stores the first 30 k-mirror numbers. For an input (k, n), it simply takes the first n numbers from that list and returns their sum, so no palindrome generation or base conversion is done at runtime.

Common mistakes to avoid and interview tips

Even though the idea sounds simple (generate palindromes and check base-k), most bugs happen in the small details below.

  • Generating palindromes incorrectly:
    • Odd vs even length mirroring confusion: For odd-length palindromes, you must skip the last digit of the half before mirroring. Otherwise, you duplicate the middle digit and create the wrong number.
    • Starting halves from the wrong range: If your half length is L, the half should typically range from 10^(L-1) to 10^L - 1 to avoid leading zeros in the final palindrome.
  • Base conversion pitfalls:
    • Forgetting the “x = 0” case: Here, we only generate positive candidates, so it won’t happen, but if you reuse conversion code elsewhere, 0 should become [0] not an empty list.
    • Checking palindrome on a string with leading zeros: Don’t pad base-k representations with zeros. Palindromes must be checked on the natural representation (no leading zeros).
  • Emphasize why you generate base-10 palindromes instead of scanning all integers: It prunes the search dramatically because base-10 palindrome density is low compared to all integers.

Frequently Asked Questions

What is a k-mirror number?

A k-mirror number is a positive integer that is a palindrome in base 10 and also a palindrome when written in base k (with no leading zeros).

Why not check every number from 1 upward?

Most numbers are not palindromes in base 10, so checking every integer wastes work. Generating palindromes directly skips the huge majority of invalid candidates.

How do you generate palindromes in base 10?

Pick a left half and mirror it. For odd-length palindromes, mirror the half excluding its last digit; for even-length palindromes, mirror the entire half.

What is the time complexity of the k-mirror solution?

The runtime depends on how many palindromes you generate before finding the first n valid numbers. In practice it is fast because n ≤ 30 and the algorithm stops early.

Does this solution work for k = 2?

Yes. You convert each base-10 palindrome candidate into base 2 digits and check whether those digits form a palindrome.

Share with others:

Leave a Reply

Your email address will not be published. Required fields are marked *