LeetCode 3260: Find the Largest Palindrome Divisible by K Solution

Master LeetCode problem 3260 (Find the Largest Palindrome Divisible by K), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3260. Find the Largest Palindrome Divisible by K

Problem Explanation

Explanation

To find the largest k-palindromic integer with n digits, we can start by constructing the first half of the palindrome and then mirror it to get the full palindrome. We need to consider two cases: when n is odd and when n is even.

  1. When n is odd:

    • For each possible first half of the palindrome, we check if it is divisible by k.
    • We start with the largest possible first half and decrement it until we find a palindrome that is divisible by k.
  2. When n is even:

    • Similar to the odd case, but we also consider the middle digit.
    • We try all possible middle digits and check if the resulting palindrome is divisible by k.

Time Complexity: O(k)
Space Complexity: O(1)

Solution Code

class Solution {
    public String largestPalindrome(int n, int k) {
        if (n == 1) {
            for (int i = 9; i >= k; i--) {
                if (i % k == 0) {
                    return Integer.toString(i);
                }
            }
            return "";
        }
        
        long maxHalf = (long) Math.pow(10, n / 2) - 1;
        for (long i = maxHalf; i > 0; i--) {
            String palindrome = i + new StringBuilder(Long.toString(i)).reverse().toString();
            long num = Long.parseLong(palindrome);
            if (num % k == 0) {
                return Long.toString(num);
            }
        }
        
        return "";
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3260 (Find the Largest Palindrome Divisible by K)?

This page provides optimized solutions for LeetCode problem 3260 (Find the Largest Palindrome Divisible by K) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3260 (Find the Largest Palindrome Divisible by K)?

The time complexity for LeetCode 3260 (Find the Largest Palindrome Divisible by K) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3260 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3260 in Java, C++, or Python.

Back to LeetCode Solutions