Problem 1432

Abstract / Summary

Given a positive integer, find the largest difference by changing one digit to any other value.

Note

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

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
18 lines | 608 bytes | submitted November 13, 2023 | GitHub   6% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (200k+ 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 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.

written by openai gpt

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.

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 = 4 | μ = 4.41 | σ = 1.89

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 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++
21 links | 9 authors | 7 languages

Videos

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

Solved On The Same Day

10 solutions   November 13, 2023

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