Find Optimal Single Digit Exchange to Maximize Value
StringsModel answerLast updated
Swap at most two digits in a non-negative integer to achieve the largest possible result.
You are given a non-negative integer represented either as an int or as a string of digits. Your task is to find the maximum value you can obtain by swapping at most one pair of digits.
Return the resulting integer after performing the optimal swap, or the original number if no beneficial swap exists.
Examples:
- Input:
2736→ Output:7236(exchange the first and second digits) - Input:
9973→ Output:9973(no swap improves the value) - Input:
1993→ Output:9913(swap the first digit with the rightmost9) - Input:
98368→ Output:98863(exchange digits at positions 2 and 4)
Constraints:
- The input is a valid non-negative integer
- You may perform zero or one swap
- Design a solution that runs in O(L) time, where L is the number of digits
What to provide:
- Your algorithm and approach
- Implementation in a language of your choice
- Time and space complexity analysis
- How you handle edge cases
Hints
Hint 1
Think about which position contributes most to the number's magnitude—where should you focus your search?
Hint 2
For a given position, if multiple candidates could be swapped in, which occurrence of that digit gives the best result?
Hint 3
Consider precomputing useful metadata about digit positions in a single pass before making your decision.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The value of a number is determined by its most significant digits first. To maximize the result, we want to place the largest possible digit as far left as we can.
Strategy:
- Scan positions from left to right (most significant to least significant)
- At each position
i, look for the largest digit appearing anywhere to the right that is strictly greater than the current digit - When such a digit is found, swap it in and stop (we're allowed at most one swap)
- If multiple occurrences of that digit exist to the right, choose the rightmost one—this keeps larger digits in more significant positions between
iand the swap target
Why the rightmost occurrence? Consider 1993. If we swap the 1 with the first 9, we get 9193. If we swap with the last 9, we get 9913, which is larger. The rightmost choice minimizes the impact on intermediate positions.
Key optimization: Precompute a lookup table last[d] storing the final index where each digit d (0–9) appears. This allows constant-time checks instead of scanning the suffix repeatedly.
Algorithm:
- Convert the number to a list of digits
- Build
last[d]for each digit 0–9 in one pass - For each position
ifrom left to right:- Try digits
dfrom 9 down tocurrent_digit + 1 - If
last[d] > i, we found a larger digit to the right - Swap positions
iandlast[d], then return immediately
- Try digits
- If no swap was made, the digits are non-increasing and already maximal
Implementation
def maximum_swap(n):
"""
Return the maximum value obtainable by swapping at most two digits.
Args:
n: int or str, a non-negative integer
Returns:
int, the maximum value after at most one swap
"""
s = str(n)
# Validate input
if not s.isdigit():
raise ValueError("Input must be a non-negative integer")
digits = list(s)
# Precompute last occurrence of each digit
last = {}
for i, digit in enumerate(digits):
last[digit] = i
# Scan from most to least significant
for i in range(len(digits)):
# Try to place the largest possible digit here
for d in '9876543210':
if d > digits[i] and d in last and last[d] > i:
# Found a beneficial swap
j = last[d]
digits[i], digits[j] = digits[j], digits[i]
return int(''.join(digits))
# No beneficial swap exists
return int(s)
Complexity Analysis
Time: O(L) where L is the number of digits
- Building the
lasttable: O(L) - Main scan: O(L) positions × O(10) digit candidates = O(L)
- The inner loop is constant time (at most 10 iterations per position)
Space: O(L)
- The digit list requires O(L) space
- The
lastdictionary holds at most 10 entries: O(1)
Edge Cases
Already optimal: 9973, 5310 (non-increasing digits)
- The scan completes without finding a beneficial swap
- Return the original value
All digits identical: 7777
- No strictly larger digit exists to the right of any position
- Return unchanged
Single digit: 5
- No swap possible
- Return as-is
Zero handling: 109 → 901, but 10 → 10
- Zeros can be swapped to the front, which is valid
Duplicate maximum digits: 1993, 98368
- The rightmost occurrence rule ensures the optimal choice
String input with leading zeros: "0089" → "9008" → 9008
- Converting to int normalizes the result
Common Mistakes
-
Using the first occurrence instead of last: Results in suboptimal swaps like
1993→9193instead of9913 -
Brute force O(L²) or worse: Trying all pairs and comparing results costs O(L²) swaps with O(L) comparison each = O(L³)
-
Forgetting the no-swap case: Must handle numbers that are already maximal
-
Swapping equal digits: The condition must be strictly greater (
d > digits[i]), not>= -
Not exiting after the first swap: The problem allows "at most one" swap, so return immediately after finding the best improvement
Follow-up: True Single-Pass Alternative
You can solve this with one right-to-left scan:
- Track the index of the maximum digit seen so far (using
>for ties to keep rightmost) - Whenever
digits[i] < max_digit, record the pair(i, max_idx) - The last recorded pair is the leftmost improvable position
- Perform that swap at the end
This avoids even the 10-entry lookup table, achieving O(L) time with O(1) extra space beyond the digit array itself.