Sum of k-Mirror Numbers - Problem

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. The representation of 9 in base-10 and base-2 are 9 and 1001 respectively, which read the same both forward and backward.

On the contrary, 4 is not a 2-mirror number. The representation of 4 in base-2 is 100, which does not read the same both forward and backward.

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

Input & Output

Example 1 — Basic Case
$ Input: k = 2, n = 5
Output: 25
💡 Note: The first 5 k-mirror numbers for k=2 are: 1 (base-10: 1, base-2: 1), 3 (base-10: 3, base-2: 11), 5 (base-10: 5, base-2: 101), 7 (base-10: 7, base-2: 111), 9 (base-10: 9, base-2: 1001). Sum = 1+3+5+7+9 = 25
Example 2 — Different Base
$ Input: k = 3, n = 7
Output: 499
💡 Note: The first 7 k-mirror numbers for k=3 are palindromes in both base-10 and base-3. We check each candidate systematically until we find 7 valid numbers.
Example 3 — Small Case
$ Input: k = 7, n = 2
Output: 4
💡 Note: For k=7, the first 2 k-mirror numbers are 1 and 3. Sum = 1+3 = 4

Constraints

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

Visualization

Tap to expand
Sum of k-Mirror Numbers INPUT Base (k) k = 2 Count needed (n) n = 5 k-Mirror Example: 9 Base-10: 9 (palindrome) Base-2: 1001 (palindrome) Find n smallest numbers that are palindromes in BOTH base-10 and base-k No leading zeros! ALGORITHM STEPS 1 Generate Base-10 Palindromes in order 2 Convert to Base-k Check binary form 3 Check Palindrome Is base-k also mirror? 4 Collect and Sum Until n numbers found Processing Numbers: Dec Binary Mirror? Sum 1 1 OK 1 3 11 OK 4 5 101 OK 9 7 111 OK 16 9 1001 OK 25 FINAL RESULT 5 Smallest k-Mirror Numbers: 1 3 5 7 9 Sum Calculation: 1 + 3 + 5 + 7 + 9 OUTPUT 25 Verification: 1: 1 (base-2) = 1 OK 3: 11 (base-2) = 11 OK 5: 101 (base-2) = 101 OK 7: 111 (base-2) = 111 OK 9: 1001 (base-2) = 1001 OK Key Insight: Generate base-10 palindromes in ascending order (1,2,3,4,5,6,7,8,9,11,22,...) since they're easier to create. For each, convert to base-k and check if it's also a palindrome. This is more efficient than checking all numbers. Build palindromes by mirroring digits: for odd-length use center digit, for even-length mirror exactly. TutorialsPoint - Sum of k-Mirror Numbers | Palindrome Generation Approach
Asked in
Google 15 Amazon 8
12.5K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen