#3260

Find the Largest Palindrome Divisible by K

Hard
MathStringDynamic ProgrammingGreedyNumber TheoryGreedyString Manipulation
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 generating all n-digit numbers, we can construct palindromes directly by manipulating their half. This reduces the number of checks significantly and allows us to focus on valid candidates only.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the largest half palindrome based on n (for odd/even n).
  2. 2Step 2: Generate the full palindrome from the half.
  3. 3Step 3: Check if the palindrome is divisible by k.
  4. 4Step 4: If not, decrement the half and repeat until a valid palindrome is found.
solution.py11 lines
1# Full working Python code
2
3def largest_palindrome_divisible(n, k):
4    half_length = (n + 1) // 2
5    start = 10**half_length - 1
6    end = 10**(half_length - 1)
7    for half in range(start, end - 1, -1):
8        palindrome = str(half) + str(half)[-1 - (n % 2):][::-1]
9        if int(palindrome) % k == 0:
10            return palindrome
11    return ""

Complexity note: The time complexity is O(n) because we only generate half of the palindrome and check for divisibility, which is much more efficient than checking all n-digit numbers.

  • 1Palindromes can be efficiently constructed by manipulating their half.
  • 2Divisibility checks can be integrated into the palindrome generation process.

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