#2081

Sum of k-Mirror Numbers

Hard
MathEnumerationEnumerationBacktracking (for generating palindromes)
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking every number, we can generate palindromic numbers directly. This reduces the search space significantly and allows us to find k-mirror numbers more efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Generate palindromic numbers by constructing them from half the digits.
  2. 2Step 2: For each generated palindrome, check if it is a palindrome in base-k.
  3. 3Step 3: Keep track of the count and sum of valid k-mirror numbers until we reach 'n'.
solution.py30 lines
1# Full working Python code
2
3def generate_palindromes(max_digits):
4    palindromes = []
5    for length in range(1, max_digits + 1):
6        half_length = (length + 1) // 2
7        for i in range(10 ** (half_length - 1), 10 ** half_length):
8            half = str(i)
9            if length % 2 == 0:
10                palindromes.append(int(half + half[::-1]))
11            else:
12                palindromes.append(int(half + half[-2::-1]))
13    return palindromes
14
15
16def k_mirror(k, n):
17    palindromes = generate_palindromes(7)  # Generate palindromes with up to 7 digits
18    count = 0
19    sum_mirror = 0
20    for num in palindromes:
21        if count >= n:
22            break
23        base_k_repr = to_base_k(num, k)
24        if is_palindrome(base_k_repr):
25            sum_mirror += num
26            count += 1
27    return sum_mirror
28
29# Example usage
30print(k_mirror(2, 5))  # Output: 25

Complexity note: The time complexity is O(n) because we generate palindromic numbers directly, significantly reducing the number of checks needed compared to the brute force approach.

  • 1Generating palindromic numbers directly reduces the search space significantly.
  • 2Understanding how to convert numbers between bases is crucial for this problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.