Largest Number After Mutating Substring
To solve this problem, the steps are:
- Traverse through the
num
string. - If
change[num[i]] > num[i]
, this means we can changenum[i]
to a bigger value. This is the beginning of the substring to mutate. - Keep mutating while
change[num[i]] >= num[i]
. This is to maximize the number. Notice the equality here because if they are equal, we continue replacing (even though there is no change) to maximize the substring that can be changed. Once this condition breaks, stop mutating and append the rest of the original string. - If we haven’t started mutating till the end of
num
, simply returnnum
as no beneficial mutation is possible.
|
|
This approach goes through the num
string once and checks each digit against the change
list, so the time complexity is O(n), where n is the length of the num
string.