![]() |
VOOZH | about |
Given a non-negative integer represented as a string s, find the smallest possible number that can be obtained by performing at most one swap of two digits.
Note: Output should not contain leading zeros.
Examples:
Input: s = "9625635"
Output: "2695635"
Explanation: Swapped the digits 9 and 2.Input: s = "1205763"
Output: "1025763"
Explanation: Swapped the digits 0 and 2.
Since only one swap is allowed, try swapping every pair of digits and generate all possible valid numbers. Among all numbers obtained after at most one swap, keep track of the smallest one and return it. This guarantees finding the minimum possible number.
2695635
Since only one swap is allowed, the leftmost digit has the highest impact on the value of the number, so we try to make the leftmost possible position as small as possible.
We greedily reduce the leftmost possible digit. First, try to improve the leading digit using the smallest non-zero digit on its right. Otherwise, find the next leftmost position that can be improved.
Step-by-step Implementation:
2695635