π Introduction
In the world of programming puzzles, palindrome-based problems always offer a unique challengeβespecially when they span across multiple number bases. Imagine trying to find numbers that not only look the same forwards and backwards in base-10, but also in base-k. Thatβs the crux of the k-mirror number challenge.
Letβs dive into the formal problem definition to see how this works:
π§ Problem Summary
You're given two integers:
-
k
: the base in which we check for palindromes -
n
: the number of k-mirror numbers to find
A k-mirror number is a positive integer that:
- Is a palindrome in base-10
- Is also a palindrome in base-k
Your task: return the sum of the first n
such numbers.
π§© Intuition
This is a palindrome-generation and filtering problem. The challenge lies in generating candidate numbers efficiently and checking their representations in different bases.
Key Observations:
- Not every decimal palindrome is a k-palindrome (i.e., palindrome in base-k)
- Instead of checking all numbers, generate only palindromes in base-10 (which drastically reduces search space)
- For each generated number, convert it to base-k and check if that string is also a palindrome
πͺ Approach
- Start from the smallest base-10 palindromes: 1-digit numbers.
- Use a helper function to generate the next decimal palindrome.
- For each candidate:
- Convert it to base-k
- Check if that base-k representation is a palindrome
- If it is, add it to the sum and count
- Stop when we find
n
such numbers
π» C++ Code
class Solution {
public:
bool isPalindrome(string s) {
return s == string(s.rbegin(), s.rend());
}
string toBaseK(long long num, int k) {
string res;
while (num > 0) {
res += to_string(num % k);
num /= k;
}
reverse(res.begin(), res.end());
return res;
}
long long kMirror(int k, int n) {
long long sum = 0;
int len = 1;
while (n > 0) {
for (int half = pow(10, (len - 1) / 2); half < pow(10, (len + 1) / 2) && n > 0; ++half) {
string h = to_string(half);
string r = h;
reverse(r.begin(), r.end());
string full = h + (len % 2 ? r.substr(1) : r);
long long num = stoll(full);
if (isPalindrome(toBaseK(num, k))) {
sum += num;
--n;
}
}
++len;
}
return sum;
}
};
π» JavaScript Code
function isPalindrome(s) {
return s === s.split('').reverse().join('');
}
function toBaseK(num, k) {
return num.toString(k);
}
var kMirror = function(k, n) {
let sum = 0;
let len = 1;
while (n > 0) {
let lower = Math.pow(10, Math.floor((len - 1) / 2));
let upper = Math.pow(10, Math.ceil((len) / 2));
for (let half = lower; half < upper && n > 0; half++) {
let h = String(half);
let r = h.split('').reverse().join('');
let full = h + (len % 2 ? r.slice(1) : r);
let num = parseInt(full);
if (isPalindrome(toBaseK(num, k))) {
sum += num;
n--;
}
}
len++;
}
return sum;
};
π Python Code
class Solution:
def kMirror(self, k: int, n: int) -> int:
def is_palindrome(s):
return s == s[::-1]
def to_base_k(num, k):
res = ""
while num:
res = str(num % k) + res
num //= k
return res
def generate_palindromes():
length = 1
while True:
for half in range(10 ** ((length - 1) // 2), 10 ** ((length + 1) // 2)):
s = str(half)
yield int(s + s[-2::-1] if length % 2 else s + s[::-1])
length += 1
ans = 0
count = 0
for num in generate_palindromes():
if is_palindrome(to_base_k(num, k)):
ans += num
count += 1
if count == n:
break
return ans
β Final Thoughts
This problem is a beautiful mix of:
- Number theory
- String manipulation
- Efficient palindrome generation
It teaches how to narrow your search space using problem constraints (generate only base-10 palindromes), and then apply filtering.
Time Complexity:
- Efficient due to base-10 palindrome generation
- Works comfortably within
n <= 30
Drop a β€οΈ if you found this helpful.
Stay tuned for more crystal-clear coding guides. Happy coding! π
Top comments (8)
Growth like this is always nice to see - honestly, seeing clean code just makes me wanna go code too.
Thanks David, Glad you liked it.
Really Loved Postiz !!!, We should connectβ€οΈ
Was waiting for your indepth Explanation, Loved it !!!
Thanks Anna!, Glad you Liked it
Explained well.
Thanks Nadeem!
Pretty cool seeing every language shown side by side, makes the problem look way less scary
Thanks Nathan, Glab you liked it!