Python 1432.py
class Solution:
def maxDiff(self, num: int) -> int:
def replace(n, x, y):
s = str(n).replace(str(x), str(y))
return n if s[0] == "0" else int(s)
# nothing smart here ...
result = 0
for x in range(10):
for y in range(10):
a = replace(num, x, y)
for x2 in range(10):
for y2 in range(10):
b = replace(num, x2, y2)
if a != 0 and b != 0:
result = max(result, abs(a - b))
return result
Difficulty
and has an acceptance rate of about 49% (200k+ submissions).
Typical patterns to solve this problem:
- Greedy
- Math
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a method maxDiff that computes the largest absolute difference obtainable by independently replacing any digit of the input integer num with any other digit (including itself). The algorithm explores all possible single-digit substitution pairs for two numbers derived from num and records the maximum absolute difference.
Core Logic
The method begins by defining a helper function replace. This function receives a number n and two digits x and y. It converts n to a string, substitutes every occurrence of x with y using the built-in str.replace, and then checks whether the resulting string would start with a '0'. If a leading zero would appear, the original number n is returned; otherwise the transformed string is converted back to an integer.
def replace(n, x, y):
s = str(n).replace(str(x), str(y))
return n if s[0] == "0" else int(s)
The main body initializes result to zero and then iterates over every possible pair of digits (x, y) for the first transformation and every possible pair (x2, y2) for the second transformation. For each pair, it calls replace to obtain two candidate numbers a and b. If both a and b are non-zero, the absolute difference abs(a - b) is computed and result is updated with the larger of the current result and this difference.
result = 0
for x in range(10):
for y in range(10):
a = replace(num, x, y)
for x2 in range(10):
for y2 in range(10):
b = replace(num, x2, y2)
if a != 0 and b != 0:
result = max(result, abs(a - b))
Finally, the method returns the accumulated result.
return result
Edge Cases Handled
The implementation explicitly guards against the creation of numbers with a leading zero. When a replacement would cause the most significant digit to become '0', the helper returns the original number unchanged, thereby preventing an invalid integer representation. This check ensures that transformations such as turning 100 into 001 are avoided.
Additionally, the algorithm skips any pair of transformed numbers where either a or b equals zero. By requiring both numbers to be non-zero before computing the difference, the code avoids scenarios where a zero result could artificially inflate the absolute difference due to the subtraction of a zero value.
Performance Optimizations
Although the algorithm explores a combinatorial space of digit replacements, it leverages Python’s highly optimized string manipulation functions. The use of str.replace provides a fast, C-level implementation for bulk character substitution, reducing the overhead compared to manual character iteration. Converting the string back to an integer only after confirming that the leading character is not '0' avoids unnecessary parsing of invalid candidates.
The early return of the original number when a leading zero would be introduced also serves as a small optimization. By bypassing the integer conversion step for such cases, the code saves the cost of an additional int() call and the associated error handling that would otherwise be required.
Overall, the design balances exhaustive exploration of digit replacement possibilities with built-in language features that keep each individual transformation efficient.
ELI5 - Simplified Explanation
Imagine having a big box of number tiles that look like a secret code. This code wants to find the biggest gap between two different versions of a number you give it. Think of it like a game where you have a number and you can pick any digit inside it and swap it for a different digit.
First, there is a little helper tool that takes your number and swaps one kind of digit to another kind. It is careful not to let the number start with a zero because that would break the rules.
The code starts by guessing every possible way to change the first version of the number by swapping one digit. After it makes that version, it does the exact same thing again to create a second version. Now it has two different numbers. It does this over and over until it has tried every single swap possible.
Every time it creates two new numbers, it measures how far apart they are on a number line. It keeps a mental note of how big that distance is. If the new gap is bigger than the last one it found, it keeps the new one. By the time it finishes checking all the combinations, it knows exactly which two versions are the furthest apart.
Code Quality
Complexity Analysis
Other Solutions
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 | Rust | TS | ||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ |
Videos
Solved On The Same Day
- problem 1436: Destination City
- problem 1446: Consecutive Characters
- problem 1450: Number of Students Doing Homework at a Given Time
- problem 1423: Maximum Points You Can Obtain from Cards
- problem 1433: Check If a String Can Break Another String
- problem 1447: Simplified Fractions
- problem 1451: Rearrange Words in a Sentence
- problem 1452: People Whose List of Favorite Companies Is Not a Subset of Another List
- problem 1483: Kth Ancestor of a Tree Node
Extra
- 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