1. Problem Summary
- Task: For a given base
k
(≥2) and integern
, find the sum of the n smallest positive integers that are palindromes both in base-10 and base-k (no leading zeros). - Category: Math + String / Palindrome construction, Base conversion, Enumeration.
- Difficulty: Hard (but tractable with structured generation).
- 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
- 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.
- 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 haven
. c. Pros: You only test numbers that already satisfy base-10 condition and in sorted order, guaranteeing the firstn
globally smallest. - 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
Notes:
- Only decimal palindromes are enumerated, massively shrinking the search space.
- Within each length
L
, numbers are yielded in numeric order, guaranteeing global ordering.
4. Time & Space Complexity
- Let
T
be the count of decimal palindromes examined until we findn
hits (empirically small for k∈[2,9], n≤30). - Base conversion per check costs
O(log_k p)
characters; palindrome check is linear in that length. - Overall: ~
O(T · log p)
time andO(log p)
space (for strings). - This comfortably passes given the tiny
n
.
5. Mistakes & Insights
- Scanning all integers instead of constructing palindromes ⇒ TLE-ish.
- Generating palindromes with leading zeros (e.g., prefixes starting at 0) ⇒ invalid results.
- Forgetting even/odd lengths: only doing one class misses many values.
- 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
- Focus areas: a. Palindrome construction patterns (even/odd). b. Controlled enumeration + ordering guarantees. c. Base conversions & digit manipulations.
- 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)