Maximum Product of Two Digits ā š¢ Beginner (1/3) ā LeetCode Daily Python Solution (the trick nobody sees)
š Jump to your level: š¢ Beginner: 0:19ā6:37 š Full written solution: https://interview-kit-fe.vercel.app/maximum-product-of-two-digits-beginner š» Code on GitHub: https://github.com/timepasshub2539-hue/leetcode-python/tree/main/maximum-product-of-two-digits-beginner Chapters: 0:00 The Problem: Maximum Product of Two Digits 0:19 š¢ Beginner: Change one digit, get a totally different answer 0:39 Why bother learning this? 0:57 What exactly is the problem asking? 1:19 The three tools we'll use 1:47 The main idea: keep track of the top two 2:12 First, let's try the simple (slower) way 2:42 Step one: break the number into digits 2:58 Step two: keep the top two updated 3:26 Step three: multiply and we're done 3:42 Quick pause ā try this yourself 3:57 Let's trace through it together 4:34 Why the one-pass method is faster 5:11 So when should you use the slower way? 5:32 Making sure our code handles tricky cases 5:56 Let's recap what we learned 6:16 Great work ā see you next time! Change one digit in the number and the answer changes completely ā so how do you actually find the two biggest digits without overcomplicating it? In this beginner-friendly LeetCode Daily walkthrough, we solve Maximum Product of Two Digits in Python two ways: the simple approach that breaks the number apart and tracks the top two digits, then the faster one-pass method ā with a full trace-through so you can see exactly why it works. You'll learn how to extract digits, maintain a running top-two, handle tricky edge cases, and know when the "slower" way is actually the right call. #LeetCode #Python #CodingInterview #DSA #LearnToCode Watch next: - Sequential Digits Explained in Python ā Sliding Window Over a String (LeetCode 1291): https://youtu.be/wgMhwxSzuKg - Lesson 11: Why Does return None Happen to Everyone?: https://youtu.be/uTHuP6xhP5M - Stop Copy-Pasting Your Own Code #shorts: https://youtu.be/CyX0a6fKeZg
Introduction
There's a particular kind of interview question that looks almost too simple to ask, and that's exactly what makes it dangerous. Maximum Product of Two Digits is one of those. On the surface, it's asking you to find two digits in a number and multiply them. No graphs, no recursion, no dynamic programming table. Just digits and multiplication.
But interviewers don't ask this question to see if you can multiply. They ask it to see whether you reach for the obvious solution or the right one. Almost everyone's first instinct is to compare every digit against every other digit ā a nested loop. It works, and for this specific problem, it's even fast enough. But the moment you generalize this pattern to "find the top K elements in a large stream of data," nested loops stop being harmless and start being the reason your service times out.
This problem is really a disguised version of a much more common interview pattern: maintain a running top-N while scanning a collection once. You'll see this exact idea again in problems like "second largest number in an array," "top two salaries," or "top K frequent elements." Learning it here, on a tiny problem with at most ten digits, means you'll recognize it instantly when it shows up somewhere much bigger.
Problem Overview
You're given a positive integer. Your task is to look at its individual digits and find the two digits whose product is the largest possible.
A few things to keep in mind:
- You're working with digits (0ā9), not the digits' positions or the number itself.
- If a digit appears more than once in the number, you're allowed to use two separate occurrences of it as your pair. For example, in
22, the digits are2and2, and you're allowed to multiply2 Ć 2. - You return a single integer: the highest product achievable from any two digits in the number.
That's the whole problem. No sorting is required, no tricks with negative numbers, no need to worry about digit order ā just digits and one multiplication.
Example
Input: 124
Digits: 1, 2, 4
Every possible pair and its product:
1 Ć 2 = 21 Ć 4 = 42 Ć 4 = 8
Output: 8, because 2 Ć 4 is the largest product among all pairs.
Input: 22
Digits: 2, 2
Only one meaningful pair here: 2 Ć 2 = 4.
Output: 4
Input: 10
Digits: 1, 0
Only pair: 1 Ć 0 = 0.
Output: 0 ā a good reminder that a zero digit anywhere will drag the product down, no matter how big the other digit is.
Intuition
Here's the mental leap that makes this problem click: you don't actually care about pairs ā you only care about the two largest individual digits.
That's because multiplication of two non-negative digits is maximized by maximizing both factors independently. If you know the single biggest digit and the single second-biggest digit in the number, their product is guaranteed to be the best possible product you can make. You never need to check every combination to know this ā it falls directly out of basic number reasoning: to maximize a Ć b where both are non-negative, you want the largest available a and the largest available b from what remains.
So the problem quietly transforms from "check all pairs" into "find the top two values in a small list." And finding the top two values in a list is a classic pattern: keep two tracking variables, sweep through the list once, and update them as you go.
Picture a tiny leaderboard with exactly two slots ā first place and second place. As each digit walks by, ask:
- Is this bigger than whoever's in first place? If so, bump first place down into second, and this digit takes first place.
- If not, is it at least bigger than second place? If so, it slides into second place.
- Otherwise, it doesn't make the leaderboard at all, and you move on.
By the time every digit has walked past, your two leaderboard spots hold exactly the two digits you need ā and you got there without ever comparing a pair.
Brute Force Solution
Idea: Try every possible pair of digits and keep the largest product.
Algorithm:
- Convert the number to a list of digits.
- Use two nested loops ā the outer loop picks one digit, the inner loop picks another.
- Multiply each pair and track the maximum product seen.
Advantages:
- Extremely easy to reason about and verify correct.
- No risk of subtle off-by-one leaderboard bugs.
Disadvantages:
- Does far more work than necessary ā it recomputes information you could have tracked in a single pass.
- Doesn't scale. This exact pattern, applied to a much larger list, becomes a real performance problem.
Complexity:
- Time: O(n²), where n is the number of digits.
- Space: O(n) to store the digit list.
For this specific problem, n is at most 10 (a number can have at most 10 digits before it likely overflows standard integer ranges used in these problems), so O(n²) is completely fine in practice. But it's worth recognizing why it's fine here ā small, fixed input size ā rather than assuming nested loops are always an acceptable default.
Optimal Solution
The optimal approach drops the nested loop entirely and replaces it with a single pass that tracks the top two digits as it goes.
Step-by-step:
- Convert the number to digits. Turn the number into a string so you can iterate over individual characters, then convert each character back into an integer.
- Initialize two trackers,
max1andmax2, both starting at0. These represent your current best and second-best digits. - Sweep through every digit once:
- If the current digit is greater than
max1, thenmax1becomes this digit, and the oldmax1gets demoted tomax2. - Otherwise, if the current digit is greater than
max2, it becomes the newmax2. - Otherwise, it's ignored ā it doesn't beat either leaderboard spot.
- If the current digit is greater than
- Multiply
max1 Ć max2once the loop finishes. That's your answer.
Here's a table tracing through 124:
| Digit | Comparison | max1 | max2 |
|---|---|---|---|
| start | ā | 0 | 0 |
| 1 | 1 > 0 ā new max1 | 1 | 0 |
| 2 | 2 > 1 ā new max1, old max1 (1) ā max2 | 2 | 1 |
| 4 | 4 > 2 ā new max1, old max1 (2) ā max2 | 4 | 2 |
Final: max1 = 4, max2 = 2, product = 8. Matches the brute force result, as it should.
The key insight that makes this correct even with duplicate digits: the demotion rule. When a new digit beats max1, the old max1 doesn't disappear ā it slides into max2. That's what keeps repeated digits like the two 2s in 22 from being lost.
Python Code
def max_product_of_two_digits(number: int) -> int:
"""Return the largest product obtainable from any two digits of `number`."""
max1 = max2 = 0
for char in str(number):
digit = int(char)
if digit > max1:
max1, max2 = digit, max1
elif digit > max2:
max2 = digit
return max1 * max2
def demo():
assert max_product_of_two_digits(124) == 8
assert max_product_of_two_digits(22) == 4
assert max_product_of_two_digits(10) == 0
assert max_product_of_two_digits(11) == 1
assert max_product_of_two_digits(987) == 72
print("all checks passed")
if __name__ == "__main__":
demo()
Code Walkthrough
max1 = max2 = 0ā both leaderboard slots start empty (represented as zero, the smallest possible digit).for char in str(number)ā converting the number to a string lets us iterate over its digits one character at a time without manual math (like repeated% 10and// 10).digit = int(char)ā turns each character back into an actual integer we can compare and multiply.if digit > max1: max1, max2 = digit, max1ā this single line does both the promotion of the new digit and the demotion of the old champion, using Python's tuple assignment to avoid a temporary variable.elif digit > max2: max2 = digitā only checked when the digit didn't beatmax1; this is where ties withmax1still get a chance to claim second place.return max1 * max2ā once every digit has been considered, multiply the two leaders.
Dry Run
Let's trace 987 step by step.
Digits: 9, 8, 7
- Start:
max1 = 0,max2 = 0 - Digit
9:9 > 0āmax1 = 9,max2 = 0(old max1) - Digit
8:8 > 9? No.8 > 0? Yes āmax2 = 8 - Digit
7:7 > 9? No.7 > 8? No ā ignored
Final: max1 = 9, max2 = 8, product = 72. ā
Complexity Analysis
Optimal solution:
- Time: O(n) ā each digit is visited exactly once, and the work done per digit (two comparisons, at most one swap) is constant.
- Space: O(1) extra ā only two integer variables (
max1,max2) are used regardless of how long the number is. (Converting to a string does use O(n) space, but that's for iteration convenience, not for the algorithm's core memory usage.)
This is correct because the leaderboard invariant holds after every digit: at any point in the loop, max1 and max2 are guaranteed to be the largest and second-largest digits seen so far. Since every digit gets a chance to challenge the leaderboard exactly once, by the end of the loop they hold the largest and second-largest digits overall.
Brute force solution:
- Time: O(n²) ā every digit is compared against every other digit.
- Space: O(n) ā storing the digit list.
Alternative Solutions
A reasonable alternative is to skip manual tracking entirely and use Python's built-in sorting:
def max_product_sorted(number: int) -> int:
digits = sorted(int(c) for c in str(number))
return digits[-1] * digits[-2]
This is shorter to write and easy to read, but it sorts the entire list ā O(n log n) time ā when you only ever need the top two values. For a number with at most 10 digits, the difference is invisible. But it's worth knowing the single-pass leaderboard approach because it generalizes: if you needed the top three or top K digits, the leaderboard idea extends naturally (or you'd reach for a heap), while re-sorting every time becomes wasteful as K and n grow.
Edge Cases
- Single-digit-repeated numbers (
11,22,99): the demotion rule correctly lets the second occurrence claimmax2, giving results like1Ć1=1,2Ć2=4,9Ć9=81. - Numbers containing zero (
10,100,205): zero digits are still tracked correctly, and if zero ends up inmax1ormax2, the final product correctly comes out to0. - Two-digit numbers (the smallest valid input, e.g.,
10through99): there are exactly two digits, so the answer is simply their product ā no ambiguity. - Large numbers with many repeated high digits (
999999): every9after the first two is simply ignored once both leaderboard spots are filled with9, and the answer stays81. - Strictly increasing or decreasing digit sequences (
123456,654321): the two highest digits are always correctly found regardless of their position in the number.
Common Mistakes
- Forgetting the demotion step. Only updating
max1when a bigger digit appears ā without shifting the oldmax1intomax2ā silently loses information and produces wrong answers on repeated digits. - Using strict inequality where a tie should still count. If you write
digit > max2but forget it should also fire whendigit == max1(as in theelifstructure above), duplicate digits like in22won't be handled correctly. - Not converting characters back to integers. Comparing string characters (
'9' > '8') technically works for single digits due to how digit characters are ordered, but it's fragile and easy to break ā always convert explicitly. - Assuming digit order matters. Some beginners try to preserve the original position of digits, when the problem only cares about their values.
- Using nested loops out of habit without checking whether a single-pass approach is possible, forming a pattern that becomes a real bottleneck on larger inputs later in your interview prep.
Interview Questions
- How would you modify this to find the top three digits and their product instead of two?
- What if the input could contain negative numbers ā how does the leaderboard logic change?
- Can you solve this without converting the number to a string, using only arithmetic operations (
% 10and// 10)? - How would this approach change if you were streaming digits one at a time and couldn't store them all?
- What's the largest possible input size where the brute force approach would actually become a real performance problem?
Similar Problems
- Second Largest Number in an Array ā the exact same leaderboard pattern applied to a general list instead of digits.
- Kth Largest Element in an Array ā a generalization of "track the top two" to "track the top K," often solved with a heap.
- Two Sum ā while different in goal, it shares the lesson that a single pass with the right tracking structure beats brute-force pair checking.
- Maximum Product of Three Numbers ā a direct extension of this exact problem's idea to three tracked values instead of two, which is the next problem in this series.
- Top K Frequent Elements ā another "find the best few without checking everything" problem, just applied to frequency counts instead of raw values.
Key Takeaways
The real lesson here isn't about digits or multiplication ā it's about recognizing when a problem is secretly asking "find the top few values in a single pass." Once you see that pattern, the nested-loop instinct disappears, and you reach directly for two (or K) tracking variables updated as you scan. That one shift in thinking ā from "compare everything" to "track the best as you go" ā is one of the most reusable ideas in all of coding interviews.
Watch the Video
If you'd rather see this traced out visually, step by step, with the leaderboard analogy animated in real time, check out the full walkthrough here: {LINK}
About the Series
This problem is part of the Daily Python LeetCode series, where a new problem is broken down every day ā starting from the intuition, moving through brute force, and landing on a clean, optimal Python solution. The goal isn't just to solve today's problem, but to build a toolbox of patterns you'll recognize instantly in future ones. Tomorrow's problem builds directly on this one, extending the same idea to three numbers instead of two.
Call To Action
If this walkthrough helped the idea click, give the video a like on YouTube and subscribe so you don't miss tomorrow's problem. For the full written breakdowns like this one delivered straight to your inbox, subscribe to the Substack newsletter. And if you know someone prepping for interviews who's stuck overusing nested loops, share this with them ā and drop a comment with what number you'd want traced through next.
The solution
def brute(n):
d = [int(c) for c in str(n)]
best = 0
for i in range(len(d)):
for j in range(len(d)):
if i != j:
best = max(best, d[i]*d[j])
return bestReady to try it yourself? Solve General problems with instant feedback in the practice sandbox.
Practice now ā


