Problem Description
We are given an integer num. Bob can remap exactly one digit (i.e. change all occurrences of one chosen digit to another digit between 0 and 9) in num. The goal is to find the difference between the maximum and minimum values Bob can achieve through such a remapping. Note that the modifications can result in numbers with leading zeros.
Key Insights
- To maximize the value, replace the first digit that is not '9' with '9' everywhere in the number.
- To minimize the value, there are two scenarios:
- If the leading digit is not '1', replace it with '1'.
- Otherwise, find the first digit (other than the leading one) that is not '0' or '1' and replace all its occurrences with '0'.
- String conversion and manipulation simplifies replacing digits and evaluating the resulting values.
Space and Time Complexity
Time Complexity: O(n), where n is the number of digits in num
Space Complexity: O(n), for storing the string representation of num
Solution
Convert the integer num into its string representation. For obtaining the maximum value, iterate over the string from left to right and find the first digit that is not '9' and replace every occurrence of that digit with '9'. For obtaining the minimum value, check if the first digit is not '1' and if so, replace all its occurrences with '1'. Otherwise, find the first digit (after the first character) that is not '0' or '1' and replace every occurrence of that digit with '0'. Finally, convert the new strings back into integers and return the difference between the maximum and minimum values.