Largest Palindrome Product - Problem

You're tasked with finding the largest palindrome that can be formed by multiplying two n-digit numbers. A palindrome reads the same forwards and backwards (like 12321 or 9009).

Given an integer n, return the largest palindromic integer that is the product of two n-digit integers. For example, if n = 2, you need to find the largest palindrome formed by multiplying two 2-digit numbers (10-99).

Since the result can be extremely large, return it modulo 1337.

Key Challenge: The brute force approach of checking all possible products becomes computationally expensive for larger values of n. We need to work backwards from the largest possible palindrome!

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 2
โ€บ Output: 987
๐Ÿ’ก Note: The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 ร— 99. Since 9009 % 1337 = 987, we return 987.
example_2.py โ€” Single Digit
$ Input: n = 1
โ€บ Output: 9
๐Ÿ’ก Note: The largest product of two 1-digit numbers is 9 ร— 9 = 81, but we need a palindrome. The largest palindromic product is 9 ร— 1 = 9.
example_3.py โ€” Three Digits
$ Input: n = 3
โ€บ Output: 181
๐Ÿ’ก Note: The largest palindrome from two 3-digit numbers is 999999 = 999 ร— 1001. Since 999999 % 1337 = 181, we return 181.

Visualization

Tap to expand
๐Ÿชž Mirror Factory: Optimal Palindrome Construction999999Largest Mirror999 ร— 1001Factory Units181Final Resultโœ“ Both 999 and 1001 are 3-digit numbersโœ“ 999999 % 1337 = 181Check factorsApply modulo
Understanding the Visualization
1
Start with Perfect Mirror
Begin with the largest possible palindromic number
2
Test Production Units
Check if the mirror can be created by multiplying two n-digit numbers
3
Verify Constraints
Ensure both factors are exactly n digits long
4
Package Result
Apply modulo 1337 to handle large numbers
Key Takeaway
๐ŸŽฏ Key Insight: Instead of building up from small products, work backwards from the largest possible palindrome and check if it can be decomposed into exactly two n-digit factors!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(10^n)

We generate palindromes by their first half, and for each palindrome we do factorization check

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space for calculations and variables

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 8
  • The result must be returned modulo 1337
  • Both factors must be exactly n-digit numbers
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 5
18.5K Views
Medium Frequency
~35 min Avg. Time
450 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