{x}
blog image

Largest Palindrome Product

Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.

 

Example 1:

Input: n = 2
Output: 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987

Example 2:

Input: n = 1
Output: 9

 

Constraints:

  • 1 <= n <= 8

Solution Explanation for Largest Palindrome Product

This problem asks to find the largest palindrome that is a product of two n-digit numbers. The solution uses a brute-force approach with optimizations to reduce the search space.

Approach:

  1. Generate Palindromes: The code iterates through numbers (a) from the maximum n-digit number down to a certain point. For each a, it constructs a palindrome x by reversing a and concatenating it to a (e.g., if a is 123, x becomes 123321).

  2. Check for Divisibility: It then iterates downwards from the maximum n-digit number (t) to check if x is divisible by t. If it is, then t and x/t are the two n-digit numbers whose product is the palindrome x.

  3. Modulo Operation: The largest palindrome found is then taken modulo 1337 as per the problem statement.

  4. Optimization: The loop for a starts from the maximum n-digit number and goes down to mx//10. This is because if a palindrome is found with a less than mx//10, a larger palindrome will exist with a larger a.

  5. Base Case: If no such palindrome is found, it returns 9 (for n=1).

Time Complexity Analysis:

The outer loop iterates approximately 10^n - 10^(n-1) times. The inner loop iterates approximately 10^n times in the worst case. Therefore, the overall time complexity is approximately O(10^(2n)). This is a brute-force approach, and the complexity is exponential with respect to n.

Space Complexity Analysis:

The space complexity is O(1), as we only use a few variables to store numbers and don't use any extra data structures that grow with the input size.

Code Explanation (Python):

class Solution:
    def largestPalindrome(self, n: int) -> int:
        mx = 10**n - 1
        for a in range(mx, mx // 10, -1):
            b = x = a  # x will store the palindrome
            while b:    # Construct the palindrome by reversing a
                x = x * 10 + b % 10
                b //= 10
            t = mx
            while t * t >= x:  # Check divisibility from mx down
                if x % t == 0:
                    return x % 1337 # Found, return modulo 1337
                t -= 1
        return 9 # No Palindrome found (n=1 case)

The other languages (Java, C++, Go) follow a very similar structure and logic. They implement the same algorithm with only minor syntax changes to suit the specific language.