Problem 2566

Abstract / Summary

Given a number, change all occurrences of one digit to another to maximize the difference between the new and original number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
10 lines | 305 bytes | submitted January 8, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 76% (100k+ submissions).

Typical patterns to solve this problem:
  • Greedy
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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:

  • low candidate: all occurrences of x in the original string are replaced with '0'.
  • high candidate: all occurrences of x in 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.52 | σ = 1.75

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
23 links | 9 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   January 8, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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