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 the Largest Palindrome Divisible by K Greedy Construction Approach INPUT n-digit Palindrome Structure d1 d2 d1 d1 = d3 (mirror) Constraint: x mod k = 0 n 3 k 5 Find largest 3-digit palindrome div by 5 ALGORITHM STEPS 1 Divisibility Rule k=5: last digit must be 0 or 5 2 Palindrome Constraint First digit = Last digit 3 No Leading Zeros First digit must be 5 4 Maximize Middle Try 9,8,7... for middle 5 9 5 Fixed fixed max fixed 595 mod 5 = 0 [OK] FINAL RESULT Largest k-Palindromic Number 595 Verification Palindrome: 595 [OK] Digits: 3 [OK] 595 / 5 = 119 [OK] Output "595" Key Insight: For k=5, divisibility requires last digit 0 or 5. Since palindrome mirrors first digit to last, and first digit cannot be 0 (no leading zeros), first and last must both be 5. Then greedily maximize remaining digits from left to right to get the largest palindrome. TutorialsPoint - Find the Largest Palindrome Divisible by K | Greedy Construction
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