Problem Description
Given an integer num, perform exactly two digit-replacement operations. In each operation, choose a digit x (0 <= x <= 9) from the current number, and choose another digit y (0 <= y <= 9) which could be the same as x, then replace every occurrence of x with y. The resulting number must not have leading zeros and it cannot be 0. Let a be the result from the first operation (intended to maximize the number) and b be the result from the second operation (intended to minimize the number). Return the maximum possible difference a - b.
Key Insights
- To maximize the number (a), identify the first digit (from left) that is not already 9 and change all of its occurrences to 9.
- To minimize the number (b), there are two cases:
- If the first digit is not 1, change all occurrences of that digit to 1.
- Otherwise, traverse the number from the second digit. Find the first digit that is not 0 or 1 and change all of its occurrences to 0.
- The operations must ensure that the result does not have a leading zero and is never 0.
- Both transformations can be done in a single scan of the number’s string representation.
Space and Time Complexity
Time Complexity: O(n), where n is the number of digits in num.
Space Complexity: O(n), due to conversion of the number to a string for processing.
Solution
The problem can be solved by converting the given integer into its string representation. For the maximum number a, scan from left to right until you find a digit other than '9'. Replace all occurrences of that digit with '9'.
For the minimum number b, if the first digit is not '1', replace all of its occurrences with '1'. If the first digit is already '1', scan from the second digit onward and replace all occurrences of the first digit found that isn’t '0' or '1' with '0'.
After obtaining both transformed numbers, convert them back to integers and compute the difference a - b.
The solution uses basic string manipulation and scanning (iteration) methods, which are efficient with a linear time complexity relative to the number of digits.