Largest Palindrome Product — LeetCode 479 Python Solution
- Problem
- #479
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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
- Input
- n = 2
- Output
- 987
- Explanation
- 99 x 91 = 9009, 9009 % 1337 = 987
Python solution
class Solution:
def largestPalindrome(self, n: int) -> int:
mx = 10**n - 1
for a in range(mx, mx // 10, -1):
b = x = a
while b:
x = x * 10 + b % 10
b //= 10
t = mx
while t * t >= x:
if x % t == 0:
return x % 1337
t -= 1
return 9Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 479. Largest Palindrome Product is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 479. Largest Palindrome Product?
- LeetCode 479. Largest Palindrome Product is rated Hard on LeetCode.
- What topics does LeetCode 479. Largest Palindrome Product cover?
- LeetCode 479. Largest Palindrome Product is tagged Math and Enumeration on LeetCode.