Python 2566.py
class Solution:
def minMaxDifference(self, num: int) -> int:
low = high = num
s = str(num)
for i in range(10):
x = str(i)
low = min(low, int(s.replace(x, "0")))
high = max(high, int(s.replace(x, "9")))
return high - low
Difficulty
and has an acceptance rate of about 76% (100k+ 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 method that computes the difference between the largest and smallest numbers obtainable by uniformly replacing all occurrences of a single digit in the original integer. The algorithm works by examining every possible digit (0-9) as a candidate for replacement, constructing two transformed numbers for each candidate-one where the digit is changed to 0 and another where it is changed to 9-and tracking the extreme values across all candidates. The final result is the arithmetic difference between the maximum and minimum transformed numbers.
Key Steps
Initialization of Tracking Variables
The method begins by assigning the input value to both low and high. These variables will hold the running minimum and maximum values discovered during the iteration.
low = high = num
Conversion to String for Replacement
To facilitate digit substitution, the integer is converted to its string representation once, avoiding repeated conversions inside the loop.
s = str(num)
Iteration Over All Digits
A fixed-size loop runs ten times, once for each decimal digit. The loop variable i is converted to a string x, which serves as the target digit for replacement.
for i in range(10):
x = str(i)
Construction of Candidate Numbers
Inside the loop, two candidate numbers are generated:
lowcandidate: all occurrences ofxin the original string are replaced with'0'.highcandidate: all occurrences ofxin the original string are replaced with'9'.
Both transformed strings are immediately cast back to integers, which naturally discards any leading zeros that may have been introduced.
low = min(low, int(s.replace(x, "0")))
high = max(high, int(s.replace(x, "9")))
Final Difference Computation
After processing all digits, the method returns the difference between the recorded maximum and minimum values.
return high - low
Edge Cases Handled
When the original number already contains the digit being replaced, the replace operation effectively changes those positions, while other digits remain untouched. This covers scenarios where the number includes multiple instances of the same digit, ensuring that all occurrences are transformed consistently.
If the number consists of a single digit, the loop still evaluates all ten possibilities, but the replace calls either leave the number unchanged (when the target digit does not match) or produce a new value (when it does). The integer conversion automatically removes any leading zeros, so a transformation that would otherwise produce a string like "00" correctly yields the integer 0.
Numbers that already contain 0 or 9 are also accommodated. Replacing a digit with the same value ('0' to '0' or '9' to '9') results in the original number, which is safely considered in the min and max updates.
Performance Optimizations Observed
The algorithm leverages a constant-size loop (exactly ten iterations), guaranteeing that the runtime does not grow with the magnitude of the input number. By converting the integer to a string a single time before the loop, it avoids repeated string construction overhead. The use of Python’s built-in min and max functions provides efficient in-place comparison without additional branching logic. Finally, the immediate conversion of the replaced strings back to integers eliminates the need for separate handling of leading zeros, simplifying the code path and reducing memory usage.
ELI5 - Simplified Explanation
Imagine you have a big secret number written on a piece of paper. You want to make this number as small as possible and as big as possible by changing one of the digits inside it.
To find the smallest number, you go through every digit from zero to nine and pretend that whenever you see that digit in your secret number, it turns into a zero. You do this for all the different digits to see which change makes the final number tiny.
To find the biggest number, you do the exact same thing, but this time you pretend every chosen digit turns into a nine. This makes the number grow as large as it can.
After you have found the smallest possible version and the biggest possible version of your number, you look at them both to see how far apart they are. You find the gap between the biggest one and the smallest one to see the difference between them.
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 | Java | Python | C++ | TS | ||||
| WalkCCC | Java | Python | C++ | ||||||
| leetcode.ca | Java | Python | JS | C++ | C | Go | Rust | TS | |
| Progiez | Java | Python | C++ | ||||||
| github | charles-wangkai | Java | |||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C, C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 2016: Maximum Difference Between Increasing Elements
Solved On The Same Day
- problem 2465: Number of Distinct Averages
- problem 2855: Minimum Right Shifts to Sort the Array
- problem 1208: Get Equal Substrings Within Budget
- problem 1277: Count Square Submatrices with All Ones
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