Problem 670

Abstract / Summary

Find the maximum number by swapping exactly one pair of digits in a given non negative integer.

Note

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

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
16 lines | 429 bytes | submitted August 15, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (900k+ 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 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 < current prevents 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 2736 where swapping the 2 and 7 yields 7236.
  • Numbers that are already maximal - If no swap can produce a larger integer, the initial result = num remains 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 num to a string once, the code avoids repeated integer-to-string transformations inside the nested loops, reducing overhead.
  • In-place maximum tracking - Maintaining a single result variable eliminates the need for auxiliary data structures to store all candidate values, keeping memory usage minimal.
  • Conditional update - The if result < current guard ensures that the assignment to result occurs only when a better value is found, avoiding unnecessary writes.
  • Early termination for single-digit inputs - The guard if num < 10 prevents 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.

written by openai gpt

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.

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 = 5 | μ = 4.96 | σ = 1.71

Complexity Analysis

Time: polynomial
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
generated automatically

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

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   August 15, 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