Problem Description
We are given a string representing a large integer and an integer array (of length 10) that maps each digit 0-9 to another digit. We can choose to mutate one contiguous substring of the given number by replacing each digit with its mapped digit. The goal is to return the largest possible integer (as a string) after performing the mutation on a single substring. If mutating any substring does not produce a larger number, we return the original number.
Key Insights
- We are allowed to perform the mutation operation on exactly one contiguous substring.
- The mutation is beneficial only when the mapped digit is strictly greater than the original digit, so we should begin mutating at the first such occurrence.
- After starting the mutation, continue as long as the change does not make the digit smaller than its original value; stop as soon as it does.
- A greedy approach works here by iterating through the number and applying the transformation at the best opportunity.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the number, since we scan through the string once. Space Complexity: O(n) for creating a mutable copy of the string (or using additional space for the result).
Solution
The solution involves a greedy approach:
- Traverse the number from left to right.
- Begin the mutation when a digit is found that, after mapping, is greater than the original digit.
- Continue mutating consecutive digits as long as the new digit is not smaller than the original.
- Once the mutation results in a lesser digit, stop the process. This method ensures that the highest possible number is obtained by transforming only the optimal contiguous substring.