Python 0670.py
class Solution:
def maximumSwap(self, num: int) -> int:
# brute-force
if num < 10:
return num
result = num
s = str(num)
for i in range(len(s)):
for j in range(i+1, len(s)):
current = int(s[0:i] + s[j] + s[i+1:j] + s[i] + s[j+1:])
if result < current:
result = current
return result
Difficulty
and has an acceptance rate of about 52% (900k+ 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 Solution class implements a method maximumSwap that receives an integer num and returns the largest possible integer obtainable by swapping at most one pair of its digits. The algorithm follows a straightforward brute-force strategy: it enumerates every distinct pair of positions, constructs the number that would result from swapping those two digits, and retains the maximum value encountered. An early exit is performed for single-digit inputs, because no swap can improve such numbers.
Key Steps
The method can be broken down into a sequence of logical stages, each reflected in a concise code fragment.
Early exit for trivial inputs
if num < 10:
return num
When num consists of a single digit, the function returns immediately, because any swap would leave the number unchanged. This guard eliminates unnecessary work for the smallest possible inputs.
Initialization of the running maximum
result = num
The variable result holds the best value found so far. It is seeded with the original number so that, even if no beneficial swap exists, the original value will be returned.
Conversion to a string representation
s = str(num)
Transforming the integer into a string enables direct indexing of individual digits. This conversion is performed once, outside the nested loops, avoiding repeated casts during iteration.
Exhaustive pairwise enumeration
for i in range(len(s)):
for j in range(i + 1, len(s)):
...
Two nested loops iterate over all ordered pairs of distinct positions (i, j) where i < j. This systematic traversal guarantees that every possible single swap is examined.
Construction of the swapped number
current = int(s[0:i] + s[j] + s[i+1:j] + s[i] + s[j+1:])
For each pair, a new string is assembled by splicing the original digit sequence:
s[0:i]captures the prefix before the first index.s[j]places the digit from the second index into the first position.s[i+1:j]preserves the segment between the two indices.s[i]inserts the digit from the first index into the second position.s[j+1:]appends the suffix after the second index.
The concatenated string is then converted back to an integer, yielding the value that would result from performing the swap.
Updating the maximum
if result < current:
result = current
If the newly formed integer exceeds the current best, result is updated. This conditional assignment ensures that only the greatest value seen so far is retained, without storing all intermediate candidates.
Final return
return result
After all pairs have been processed, the method returns the highest value discovered, which corresponds to the optimal single swap (or the original number if no improvement is possible).
Edge Cases Handled
The algorithm naturally accommodates several subtle scenarios:
- Numbers with identical digits - Swapping two equal digits yields the same number; the comparison
result < currentprevents unnecessary updates, leaving the original value unchanged. - Numbers where the optimal swap involves the most significant digit - By iterating from the leftmost index outward, swaps that place a larger digit at a higher place value are considered, ensuring that the maximum possible increase is captured.
- Numbers where the best move is to swap a trailing smaller digit with an earlier larger digit - The exhaustive pairwise loop evaluates every combination, including those that move a larger digit forward and a smaller digit backward, covering cases such as
2736where swapping the2and7yields7236. - Numbers that are already maximal - If no swap can produce a larger integer, the initial
result = numremains unchanged, and the method returns the input unchanged.
Performance Optimizations Observed
Although the approach is brute-force, the implementation includes a few practical efficiencies:
- Single conversion to string - By converting
numto a string once, the code avoids repeated integer-to-string transformations inside the nested loops, reducing overhead. - In-place maximum tracking - Maintaining a single
resultvariable eliminates the need for auxiliary data structures to store all candidate values, keeping memory usage minimal. - Conditional update - The
if result < currentguard ensures that the assignment toresultoccurs only when a better value is found, avoiding unnecessary writes. - Early termination for single-digit inputs - The guard
if num < 10prevents the algorithm from entering the double loop when there is nothing to compute, saving time for the most trivial case.
These choices streamline the execution path while preserving the exhaustive nature of the search.
ELI5 - Simplified Explanation
Imagine you have a long row of number blocks sitting on a table. The goal is to make the biggest number possible by picking two of those blocks and swapping their spots.
The code starts by looking at the whole line of number blocks. It picks the first block and tries swapping it with every single block that comes after it to see if the new number gets bigger. If the number gets bigger, the code remembers the new, better version.
After it finishes trying every spot for the first block, it moves to the second block and swaps that with everything after it, then the third, and keeps going until it has tried every possible swap. Because the code wants to find the absolute biggest number, it keeps track of the highest one it creates during all of these trials. Once it has checked every single combination, it holds onto the largest number it managed to build.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
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 | Python | JS | Rust | Go | TS | ||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fengvyi | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| JoshCrozier | JS | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fengvyi | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| JoshCrozier | JavaScript | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 321: Create Maximum Number
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
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