#479
Largest Palindrome Product
HardMathEnumerationBrute ForceMath
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n²)Space O(1)
The optimal solution leverages the properties of palindromes and the structure of n-digit numbers to reduce the number of products we need to check. Instead of checking all pairs, we can start from the largest numbers and work our way down, stopping early when we find a valid palindrome.
⚙️
Algorithm
6 steps- 1Step 1: Determine the range of n-digit numbers, which is from 10^(n-1) to 10^n - 1.
- 2Step 2: Initialize a variable to keep track of the largest palindrome found.
- 3Step 3: Iterate through n-digit numbers in descending order, starting from the largest.
- 4Step 4: For each number, generate potential palindromic products by constructing palindromes directly.
- 5Step 5: Check if the palindrome can be formed by multiplying two n-digit numbers.
- 6Step 6: Return the largest palindrome found modulo 1337.
solution.py13 lines
1# Full working Python code
2
3def largest_palindrome_product(n):
4 max_palindrome = 0
5 upper_limit = 10**n - 1
6 for i in range(upper_limit, 10**(n-1) - 1, -1):
7 for j in range(i, 10**(n-1) - 1, -1):
8 product = i * j
9 if product <= max_palindrome:
10 break
11 if str(product) == str(product)[::-1]:
12 max_palindrome = max(max_palindrome, product)
13 return max_palindrome % 1337ℹ
Complexity note: The time complexity remains O(n²) due to the nested loops, but we are reducing unnecessary checks by breaking early when we find a palindrome. The space complexity is O(1) as we are only using a few variables.
- 1Palindromes are symmetric, which can help reduce the number of checks needed.
- 2Starting from the largest numbers allows us to find the largest palindrome sooner.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.