DEV Community

Alex Hunter
Alex Hunter

Posted on

2081. Sum of k-Mirror Numbers: LeetCode Study Note by LeetCopilot

1. Problem Summary

  1. Task: For a given base k (≥2) and integer n, find the sum of the n smallest positive integers that are palindromes both in base-10 and base-k (no leading zeros).
  2. Category: Math + String / Palindrome construction, Base conversion, Enumeration.
  3. Difficulty: Hard (but tractable with structured generation).
  4. Key constraints (from problem/typical limits): a. 2 ≤ k ≤ 9, 1 ≤ n ≤ ~30. b. We only need the first n k-mirror numbers ⇒ allows targeted enumeration rather than full search.

2. Approaches & Strategies

  1. Naïve check-everything: Iterate x = 1,2,…; test if x is palindrome in base-10 and base-k. a. Cons: Far too slow; you test many non-palindromes in base-10.
  2. Generate base-10 palindromes in ascending order (optimal): a. Construct palindromes by length (L = 1,2,3,…) using a numeric prefix mirroring trick (even/odd lengths). b. For each palindrome p, convert to base-k and check palindrome; collect until we have n. c. Pros: You only test numbers that already satisfy base-10 condition and in sorted order, guaranteeing the first n globally smallest.
  3. Why this works well: a. Palindromes of length L are < any palindrome of length L+1, so a simple outer loop on L yields increasing numbers. b. With the given n (≤ ~30), we finish quickly.

3. My Solution & Code

Strategy: Generate base-10 palindromes by length; for each candidate, check base-k palindromicity via fast base conversion. Stop after finding n matches and return their sum.

def sum_k_mirror(k: int, n: int) -> int:
    # ---------- helpers ----------
    def to_base(x: int, base: int) -> str:
        if x == 0: return "0"
        ds = []
        while x:
            ds.append(str(x % base))
            x //= base
        return "".join(reversed(ds))

    def is_pal(s: str) -> bool:
        return s == s[::-1]

    def is_pal_in_base_k(x: int) -> bool:
        return is_pal(to_base(x, k))

    # Generate all base-10 palindromes with exact length L, in ascending order.
    def gen_palindromes_len(L: int):
        if L == 1:
            for d in range(1, 10):
                yield d
            return
        half = L // 2
        start = 10 ** (half - 1)
        end = 10 ** half
        if L % 2 == 0:
            for prefix in range(start, end):
                s = str(prefix)
                yield int(s + s[::-1])
        else:
            for prefix in range(start, end):
                s = str(prefix)
                for mid in range(10):
                    yield int(s + str(mid) + s[::-1])

    # ---------- main enumeration ----------
    found = 0
    total = 0
    L = 1
    while found < n:
        for p in gen_palindromes_len(L):
            if is_pal_in_base_k(p):
                total += p
                found += 1
                if found == n:
                    return total
        L += 1
Enter fullscreen mode Exit fullscreen mode

Notes:

  1. Only decimal palindromes are enumerated, massively shrinking the search space.
  2. Within each length L, numbers are yielded in numeric order, guaranteeing global ordering.

4. Time & Space Complexity

  1. Let T be the count of decimal palindromes examined until we find n hits (empirically small for k∈[2,9], n≤30).
  2. Base conversion per check costs O(log_k p) characters; palindrome check is linear in that length.
  3. Overall: ~O(T · log p) time and O(log p) space (for strings).
  4. This comfortably passes given the tiny n.

5. Mistakes & Insights

  1. Scanning all integers instead of constructing palindromes ⇒ TLE-ish.
  2. Generating palindromes with leading zeros (e.g., prefixes starting at 0) ⇒ invalid results.
  3. Forgetting even/odd lengths: only doing one class misses many values.
  4. Inefficient base conversion: repeated string concatenation in the wrong direction; the provided method collects digits then reverses once.

Key takeaways:

a. Targeted construction beats blind search for structured sets (palindromes).

b. When “first n smallest” is required, ensure generation order is sorted to avoid extra storage/sorting.

6. What’s Next

  1. Focus areas: a. Palindrome construction patterns (even/odd). b. Controlled enumeration + ordering guarantees. c. Base conversions & digit manipulations.
  2. Related LeetCode practice: a. 866. Prime Palindrome (Medium) – Generate decimal palindromes and check primality; reinforces palindrome generation + pruning. b. 906. Super Palindromes (Hard) – Enumerate palindromic roots to find palindromic squares in a range; advanced construction + bounds. c. 564. Find the Closest Palindrome (Hard) – Construct candidate palindromes near a given number; deepens understanding of prefix mirroring and edge cases.

I created this study note using LeetCopilot, an AI-powered chrome extension for LeetCode study and interview prep. LeetCopilot generate high-quality, personalized and structured study note for each problem, based on your learning history. Create you own study note with LeetCopilot today :)

Top comments (0)