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
k-Mirror Numbers: Palindromes in Both Base-10 and Base-kInput: k=2, n=31Base10: 1Base2: 12Base10: 2Base2: 103Base10: 3Base2: 114Base10: 4Base2: 1005Base10: 5Base2: 101✓ Mirror✗ Not Mirror✓ Mirror✗ Not Mirror✓ MirrorFirst 3 k-mirror numbers: 1, 3, 5Sum = 1 + 3 + 5 = 9Output: 9
Understanding the Visualization
1
Input
Given k=2, n=3 - find first 3 numbers palindromic in both base-10 and base-2
2
Process
Test candidates: 1✓, 2✗, 3✓, 4✗, 5✓, 6✗, 7✓, 8✗, 9✓
3
Output
Sum first 3: 1+3+5 = 9
Key Takeaway
🎯 Key Insight: Generate base-10 palindromes systematically instead of testing every number
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