You are given a non-negative integer num
represented as a string. You can swap two digits at most once to get the maximum valued number. Return the maximum valued number you can get.
Example 1:
Input: num = "2736"
Output: "7236"
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: num = "9973"
Output: "9973"
Explanation: No swap needed.
Constraints:
0 <= num <= 10^8
num
is always a string.num
is a non-negative integer represented as a string, and given the nature of the problem, leading zeros should not occur.def maximumSwap(num: str) -> str:
# Convert the string to a list of characters to make manipulation easier
num_list = list(num)
n = len(num_list)
# Create a dictionary to track the last index of each digit in the string
last = {int(d): i for i, d in enumerate(num_list)}
# Traverse the string from the beginning to find where to make the swap
for i, d in enumerate(num_list):
# Check for any larger digit after the current position
for digit in range(9, int(d), -1):
if last.get(digit, -1) > i:
# Swap the current digit with the larger digit found
num_list[i], num_list[last[digit]] = num_list[last[digit]], num_list[i]
# Convert list back to string and return the result
return ''.join(num_list)
# If no swap has been made, return the original number
return num
# Example usage
print(maximumSwap("2736")) # Output: "7236"
print(maximumSwap("9973")) # Output: "9973"
last
dictionary takes O(n) time where n
is the length of the string.n
times and inner loop is bounded by a constant, i.e., 10 digits).n
is the length of the string num
.last
dictionary which holds up to 10 entries (one for each digit from 0 to 9), making the space complexity O(1).num_list
takes O(n) space to store the characters of the input string.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?