Find the Largest Palindrome Divisible by K - Problem

You are given two positive integers n and k.

An integer x is called k-palindromic if:

  • x is a palindrome
  • x is divisible by k

Return the largest integer having n digits (as a string) that is k-palindromic.

Note that the integer must not have leading zeros.

Input & Output

Example 1 — Basic Case
$ Input: n = 3, k = 5
Output: 595
💡 Note: Need 3-digit palindrome divisible by 5. Since divisible by 5 requires last digit 0 or 5, and palindrome means first=last, we need first=last=5. To maximize, set middle=9. Result: 595.
Example 2 — Single Digit
$ Input: n = 1, k = 4
Output: 8
💡 Note: Need largest 1-digit number divisible by 4. The largest is 8 (8÷4=2).
Example 3 — Even Length
$ Input: n = 4, k = 6
Output: 8778
💡 Note: Need 4-digit palindrome divisible by 6. Must be divisible by both 2 and 3. Try largest possible: 8778. Sum of digits: 8+7+7+8=30, divisible by 3 ✓. Last digit 8 is even ✓. 8778÷6=1463 ✓.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ k ≤ 9

Visualization

Tap to expand
Find Largest 3-Digit Palindrome Divisible by 5Input:n = 3k = 5Constraints:• 3 digits• Palindrome• Divisible by 5Logic:Div by 5 → end in 0,5Palindrome → first=lastMaximize → middle=9595First digitMiddle digitLast digitOutput: "595"Verification: 595 is palindrome ✓, 595 ÷ 5 = 119 ✓
Understanding the Visualization
1
Input Analysis
n=3 digits, k=5 (divisible by 5)
2
Apply Constraints
Palindrome + divisible by 5 + maximize
3
Construct Answer
Result: 595
Key Takeaway
🎯 Key Insight: Use divisibility rules to constrain digit choices, then maximize within those constraints
Asked in
Google 42 Amazon 38 Microsoft 35 Meta 28
23.4K Views
Medium Frequency
~35 min Avg. Time
847 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