Skip to content
Problem 479 · LeetCode 479(opens in a new tab)

Largest Palindrome Product

HardMath

A palindrome reads the same forwards and backwards, like 4554. You are given n. Among all products of two numbers that each have exactly n digits, find the largest product that is a palindrome.

That product can have up to 16 digits, so return it modulo 1337.

Example 1

Input:  n = 3
Output: 123
Why:    993 × 913 = 906609, and 906609 % 1337 = 123
1 more example and the constraints

Example 2

Input:  n = 4
Output: 597
Why:    9999 × 9901 = 99000099, and 99000099 % 1337 = 597

Constraints

  • 1 ≤ n ≤ 8

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Products from the topO(10²ⁿ)
  2. Build palindromes, test divisorsO(k · 10ⁿ)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeMeasured work at n = 8Verdict
Products from the topO(10²ⁿ)
Passes, but slowly
Build palindromes, test divisorsO(k · 10ⁿ)
Best; far fewer candidates

n = digits in each factor; k = palindromes tried before the answer. Work counts products formed versus divisions tried.

Edge cases to test

  • n = 1. The answer is 9 (3 × 3, or 1 × 9), a 1-digit palindrome. Building 2-digit palindromes finds nothing.
  • Overflow. At n = 8 products reach 16 digits. Use 64-bit integers, or BigInt in JavaScript.
  • Modulo at the end. Compare full palindromes and take % 1337 only on the one you return.
  • Both factors must have n digits. Stopping at i × i < p keeps the cofactor p / i no larger than i, and it cannot drop below 10ⁿ⁻¹.

Common mistakes

  • Comparing products after taking % 1337, which scrambles their order.
  • Using 32-bit ints, or plain JavaScript numbers, for 16-digit products.
  • Forgetting the n = 1 case, where the even-length search returns nothing.

How to talk through it

  1. 1Clarify. Must both factors have exactly n digits? Is the modulo applied only to the final answer?
  2. 2Give the brute force. Multiply pairs from the top and test each product; it works but tries a huge number of pairs.
  3. 3Flip the search. Palindromes are rare and ordered by their left half, so list them from the largest instead.
  4. 4Bound the divisor loop. Only try i while i × i ≥ p; past that, the other factor would be bigger than 10ⁿ − 1.
  5. 5Test out loud. Run n = 1, then n = 2 (9009 = 99 × 91), and mention 64-bit math for n = 8.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?