Problem 479

Abstract / Summary

Find the largest palindrome made from multiplying two n digit numbers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0479.py

class Solution:
    def largestPalindrome(self, n: int) -> int:
        # cheating possible:
        # only 8 valid inputs, just create 8 test cases and write down the results ...

        # by trial'n'error I saw that the palindrome has always 2n digits (except when n = 1)
        if n == 1:
            return 9 # 1 * 9 = 9 % 1337

        high = int("9" * n)     # e.g. n = 3: 999
        for current in range(high, 0, -1):
            # create palindrome
            s = str(current)
            palindrome = int(s + s[::-1])

            for factor in range(current | 1, high, 2): # factors are always odd, therefore +2
                if palindrome % factor == 0 and palindrome // factor <= high:
                    return palindrome % 1337
18 lines | 767 bytes | submitted March 27, 2024 | GitHub   63% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 38% (80k+ submissions).

Typical patterns to solve this problem:
  • Enumeration
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic problem of finding the largest palindrome that can be expressed as the product of two n-digit integers. After locating that palindrome, the function returns its value reduced modulo 1337. The algorithm is tailored for the constraints of the problem and incorporates several shortcuts that reduce the search space dramatically.

Core Logic

The entry point is the method largestPalindrome. The first conditional handles the smallest possible input size:

if n == 1:
    return 9   # 1 * 9 = 9 % 1337

When n equals 1, the only one-digit numbers are 1 through 9, and the maximum palindrome product is 9. The function returns this value directly, bypassing the general search.

For larger values of n, the algorithm constructs the highest n-digit number by repeating the digit 9 n times:

high = int("9" * n)     # e.g. n = 3: 999

The outer loop iterates downward from this maximum value, treating each candidate as the left half of a potential palindrome:

for current in range(high, 0, -1):
    s = str(current)
    palindrome = int(s + s[::-1])

The string representation of current is concatenated with its reverse, guaranteeing a palindrome with exactly 2 × n digits (the exception for n == 1 has already been handled). The integer palindrome is the product candidate that will be tested for factorability.

The inner loop searches for a valid factor pair. It starts from current | 1, which forces the starting value to be odd, and steps by 2, thereby examining only odd divisors:

for factor in range(current | 1, high, 2):
    if palindrome % factor == 0 and palindrome // factor <= high:
        return palindrome % 1337

If factor divides the palindrome evenly and the complementary factor (palindrome // factor) does not exceed the maximum n-digit number, the palindrome is confirmed as a product of two n-digit numbers. The function then returns the required modulo result.

Edge Cases

The special case n == 1 is explicitly addressed, returning 9 without entering the main search loops. This avoids unnecessary computation for the trivial input size.

The palindrome construction assumes a length of 2 × n digits, which holds for all n > 1. The algorithm therefore never generates palindromes with fewer digits, eliminating the need to handle shorter candidates.

The inner loop’s condition palindrome // factor <= high ensures that both factors remain within the n-digit range. This check automatically discards any factor pair where the second factor would have more than n digits, preventing false positives.

Performance Optimizations

The descending outer loop means the first palindrome that satisfies the factor condition is guaranteed to be the largest possible, allowing an immediate return and avoiding a full enumeration of all candidates.

Limiting the inner loop to odd numbers reduces the number of divisor checks by roughly half. The expression current | 1 forces the start of the range to be odd regardless of whether current itself is even, and the step size of 2 maintains oddness throughout the iteration.

By constructing the palindrome directly from the string representation of current, the algorithm avoids costly arithmetic operations for reversal, leveraging Python’s efficient string slicing.

The modulo operation is performed only once, at the moment a valid palindrome is found, rather than repeatedly during the search. This minimizes the overhead associated with modular arithmetic.

Overall, the combination of early exit, narrowed divisor set, and concise palindrome generation yields a solution that runs quickly even for the upper limits of n allowed by the problem constraints.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of numbers and you want to find the largest one that reads exactly the same forward and backward. These special numbers are called palindromes. Think of a palindrome like a mirror because the left side reflects the right side perfectly.

When you start with a specific size for your numbers, the code first makes the largest possible starting number. If you are looking for three-digit pieces to multiply, it begins with nine hundred ninety-nine. It takes that number and sticks it together with its own reflection to build a big new number that is definitely a palindrome.

After building this mirror number, the code needs to check if it was made by multiplying two smaller numbers that fit the rules. It uses a loop to try out different smaller numbers as partners. It checks if the big mirror number can be divided perfectly by one of these partners without leaving any leftovers behind. If it finds a pair that works, it stops looking because it already found the biggest one possible. There is a tiny bit of math magic involved where it keeps track of these numbers and shares the final answer based on a specific secret remainder rule.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.59 | σ = 1.93

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
JoshCrozier JS
linouk23 C++
qiyuangong Java
ruoru Rust
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
JoshCrozier JavaScript
linouk23 C++
qiyuangong Java
ruoru Rust
suxrobGM C#
wisdompeak C++
26 links | 14 authors | 8 languages

Videos

2 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 medium 2 hard
5 solutions   March 27, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality