Maximum Product of Two Digits (LeetCode 3536): Solution and Explanation

Easy
Math
Sorting

Given a positive integer n, return the largest product of two digits taken from two different positions of n.

Intuition

Digits are never negative, so a bigger factor never makes a product smaller. The best pair is simply the two largest digits.

That turns the problem into finding the top two values in a short list, which one pass with two variables can do.

A repeated digit counts as two separate candidates. If 7 appears twice, both seats can hold a 7 and the answer is 49.

Approach: Track the top two digits

  1. Set a = 0 (largest digit) and b = 0 (second largest).
  2. While n > 0, read the last digit d = n % 10.
  3. If d > a, move a down into b and put d in a.
  4. Otherwise, if d > b, replace b with d.
  5. Drop the digit with n //= 10, then return a * b after the loop.

Step-by-step example

n = 31
  1. a = 0, b = 0.
  2. The last digit is 1. 1 > a = 0, so a becomes 1 and b becomes 0.
  3. n is now 3. The digit 3 > a = 1, so a becomes 3 and the old a slides down: b = 1.
  4. n is 0, the loop ends and we return 3 * 1 = 3.

Code: Python, Java, C++

1class Solution:
2    def maxProduct(self, n: int) -> int:
3        a = b = 0
4        while n > 0:
5            d = n % 10
6            if d > a:
7                a, b = d, a
8            elif d > b:
9                b = d
10            n //= 10
11        return a * b
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(log n)

The loop runs once per digit, and n has at most 10 digits.

Space

O(1)

Only the two seats a and b and the current digit are stored.

Other approaches

Sort the digits (time O(d log d), space O(d))

Turn n into a list of digits, sort it, and multiply the last two. It is short and clear, but sorting is more work than one pass.

Digit counting (time O(d + 10), space O(1))

Count how many times each digit 0 to 9 appears, then walk from 9 down and take the first two available digits. Useful when the input is a long digit string.

Common mistakes

  • Forgetting to move the old leader into b when a new largest digit arrives, which loses a valid second factor.
  • Deduplicating the digits. A repeated digit is a second candidate, so 22 must give 4, not 0.
  • Treating zeros specially. A zero simply never beats a seat, and if only one nonzero digit exists the answer is correctly 0.

Frequently asked questions

Why is the answer always the two largest digits?

Every digit is between 0 and 9, so making either factor larger can only keep the product the same or increase it.

Can the answer be 0?

Yes. For n = 10 or n = 1000000000 there is only one nonzero digit, so any pair includes a 0.

Is converting n to a string acceptable?

Yes. Looping over the characters works just as well. The % 10 version avoids the allocation and shows the standard digit peeling pattern.