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
Palindrome Construction Visualization9959599Symmetric ConstructionKey Insights:โ€ข Start with largest possible outer digitsโ€ข Mirror each digit to maintain palindrome propertyโ€ข Apply divisibility rules (e.g., k=5 โ†’ ends with 5 or 0)โ€ข Fill center last for odd-length strings
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.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
31.5K Views
Medium Frequency
~25 min Avg. Time
890 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