Find the Largest Palindrome Divisible by K - Problem
You're tasked with finding the largest palindromic number with exactly n digits that is divisible by k.
A number is k-palindromic if it satisfies two conditions:
- It reads the same forwards and backwards (palindrome)
- It's evenly divisible by
k
For example, with n = 3 and k = 5, the answer would be "595" because it's the largest 3-digit palindrome divisible by 5.
Important: The result cannot have leading zeros, so it must be a valid n-digit number.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 3, k = 5
โบ
Output:
"595"
๐ก Note:
The largest 3-digit palindrome divisible by 5. Since divisible by 5 means ending in 0 or 5, and we want the largest, we choose 5 for both ends. The middle digit should be as large as possible, which is 9.
example_2.py โ Even Divisor
$
Input:
n = 4, k = 2
โบ
Output:
"8998"
๐ก Note:
For divisibility by 2, the number must be even. The largest 4-digit even palindrome has 8 at both ends (since 9998 would be odd). The middle two digits can both be 9.
example_3.py โ Single Digit
$
Input:
n = 1, k = 7
โบ
Output:
"7"
๐ก Note:
With only one digit, we need the largest single digit divisible by 7, which is 7 itself.
Constraints
- 1 โค n โค 105
- 1 โค k โค 9
- The result must have exactly n digits (no leading zeros)
- The result must be both a palindrome and divisible by k
Visualization
Tap to expand
Understanding the Visualization
1
Foundation
Place the largest valid digits at the ends
2
Symmetry
Work inward, mirroring each digit placement
3
Constraints
Ensure divisibility rules are maintained
4
Completion
Fill the center digit for odd-length palindromes
Key Takeaway
๐ฏ Key Insight: By understanding divisibility rules and constructing the palindrome greedily from outside to inside, we can build the optimal solution without checking all possibilities.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code