Taro Logo

Largest Number After Mutating Substring

#19 Most AskedMedium
0 views
Topics:
StringsGreedy Algorithms

You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d].

You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]).

Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num.

A substring is a contiguous sequence of characters within the string.

Example 1:

Input: num = "132", change = [9,8,5,0,3,6,4,2,6,8]
Output: "832"
Explanation: Replace the substring "1":
- 1 maps to change[1] = 8.
Thus, "132" becomes "832".
"832" is the largest number that can be created, so return it.

Example 2:

Input: num = "021", change = [9,4,3,5,7,2,1,9,0,6]
Output: "934"
Explanation: Replace the substring "021":
- 0 maps to change[0] = 9.
- 2 maps to change[2] = 3.
- 1 maps to change[1] = 4.
Thus, "021" becomes "934".
"934" is the largest number that can be created, so return it.

Example 3:

Input: num = "5", change = [1,4,7,5,3,2,5,6,9,4]
Output: "5"
Explanation: "5" is already the largest number that can be created, so return it.

Constraints:

  • 1 <= num.length <= 105
  • num consists of only digits 0-9.
  • change.length == 10
  • 0 <= change[d] <= 9

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum possible length of the string `num` and the format of the `change` array?
  2. Can the mutation result in a string with leading zeros, or should leading zeros be preserved as part of the integer representation?
  3. Is it mandatory to mutate a substring, or are we allowed to choose not to mutate anything at all if all mutations decrease the value of the number?
  4. If multiple choices of substrings can yield the same maximum resulting number, does it matter which one we return?
  5. Can digits in the `change` array map a digit to itself (e.g., mapping `3` to `3`), and how should we treat cases where `change[d] > d` versus `change[d] >= d`?

Brute Force Solution

Approach

Imagine you have a long number written on a paper strip and a special rulebook that lets you swap certain digits for bigger ones. The brute force approach involves testing every single possible section of the number to see what happens when you apply your upgrade rules to it.

Here's how the algorithm would work step-by-step:

  1. Look at the original number as a sequence of single-digit tiles lined up side by side.
  2. Find every possible starting point and ending point to define a continuous slice of the number.
  3. For each of these possible slices, go through every digit inside it and check your rulebook to see if you are allowed to replace it with a larger digit.
  4. If a replacement is allowed and the new digit is actually bigger than the original one, make the swap for that specific slice.
  5. Write down or remember the final combined number resulting from each tested slice.
  6. Compare all the newly formed numbers side by side to see which one has the greatest value.
  7. Declare the absolute biggest number you found during this exhaustive search as your final answer.

Code Implementation

def maximum_number(number_string, replacement_rules):
    candidate_results = [number_string]

    # Generate every continuous slice to test all possible substring mutation ranges
    for start_index in range(len(number_string)):
        for end_index in range(start_index + 1, len(number_string) + 1):

            current_digits = list(number_string)
            mutation_started = False
            mutation_stopped = False

            # Evaluate each digit within the chosen slice against the replacement rules
            for digit_index in range(start_index, end_index):
                original_digit_character = current_digits[digit_index]
                original_digit_integer = int(original_digit_character)
                replacement_digit_integer = replacement_rules[original_digit_integer]
                replacement_digit_character = str(replacement_digit_integer)

                if replacement_digit_integer > original_digit_integer:
                    current_digits[digit_index] = replacement_digit_character
                    mutation_started = True
                elif replacement_digit_integer < original_digit_integer and mutation_started:
                    mutation_stopped = True
                    break
                elif replacement_digit_integer == original_digit_integer and mutation_started:
                    pass

            if mutation_started:
                candidate_results.append("".join(current_digits))
            if mutation_stopped and start_index == end_index - 1:
                pass

    # Compare all generated candidate strings lexicographically to find the absolute maximum value
    return max(candidate_results)

Big(O) Analysis

Time Complexity
O(n²) – To evaluate every possible continuous slice of the number, we use nested processes where the outer choice sets all possible starting points and the inner choice defines every ending point for a length of n digits. For a string of length n, there are roughly n * (n + 1) / 2 unique slices to test, and for each slice, we iterate through its digits to apply the mutation rules. This exhaustive search leads to approximately n * n / 2 total operations, which ultimately simplifies to O(n²) time complexity.
Space Complexity
O(N) – The algorithm requires storing intermediate representations of the number during the exhaustive search of every possible slice and comparison step. Specifically, generating and comparing the newly formed number strings requires allocating temporary string objects of length N, where N is the number of digits in the original input. Since these mutated substrings are stored in memory to find the maximum value, the auxiliary space scales linearly with the input size N. Thus, the total extra memory simplifies to Big O of N.

Optimal Solution

Approach

To make the number as large as possible, we should scan the digits from left to right and replace a portion of them with larger mapped values if possible. The key is to start the replacement the exact moment a mapped digit becomes strictly larger than the original digit, and stop the moment a mapped digit becomes smaller.

Here's how the algorithm would work step-by-step:

  1. Read through the digits of the number from left to right, looking for the first digit that can be upgraded to a strictly larger value using the given rule.
  2. Once you find a digit that gets bigger, start replacing consecutive digits as long as the new mapped value is greater than or equal to the original digit.
  3. If you encounter a digit where the mapped value is actually smaller than the current digit, stop the replacement process immediately because making a digit smaller further to the left ruins the overall value.
  4. If you reach the end of the number while still making upgrades, simply stop there.
  5. Combine the untouched beginning, the newly upgraded middle section, and the untouched ending to form your final largest possible number.

Code Implementation

def maximum_number(number_string: str, change_mapping: list) -> str:
    digits_list = list(number_string)
    is_mutating = False

    # Iterate through digits to find the optimal window for maximizing value.
    for index in range(len(digits_list)):
        current_digit = int(digits_list[index])
        mapped_digit = change_mapping[current_digit]

        if mapped_digit > current_digit:
            digits_list[index] = str(mapped_digit)
            is_mutating = True
        elif mapped_digit == current_digit and is_mutating:
            continue
        elif is_mutating:
            # Stop mutation immediately when a mapped value becomes smaller.
            break

    return "".join(digits_list)

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by a single pass through the string of digits of length n to find the start of the substitution, followed by continuing that same traversal to apply replacements until a smaller mapped value is encountered. We iterate through the digits at most once from left to right. This single sequential scan requires approximately n operations. Therefore, the total operations simplify to Big O of n.
Space Complexity
O(N) – To construct the final largest number, we convert the input string of digits into a mutable character array or string builder of length N, where N is the number of digits in the input. This temporary sequence stores the untouched, upgraded, and remaining digits as we scan from left to right. Aside from a few constant-space tracking variables used in our iteration loop, this character collection represents the primary extra memory allocated during execution. Thus, the auxiliary space scales linearly with the input size N, simplifying to Big O of N.

Edge Cases

No digits are beneficial to change
How to Handle:
The algorithm simply does not mutate any substring and returns the original string unchanged.
Mutating the entire string provides the maximum value
How to Handle:
The substring search continues to the end of the string and successfully mutates every digit.
A valid substring mutation starts and then immediately encounters a digit where change[d] < d
How to Handle:
The greedy approach stops the mutation window immediately to prevent decreasing the number value.
Multiple disjoint substrings could theoretically be mutated
How to Handle:
The problem statement restricts operations to at most one contiguous substring, so we only select the single best continuous segment.
The string consists of a single digit
How to Handle:
The algorithm checks that single digit against its mapping and replaces it only if the mapped value is strictly greater.
Mapping replaces digits with equal values
How to Handle:
The condition checks for strict inequality change[d] > d to start the mutation, avoiding unnecessary mutations that do not increase value.
Maximum length strings up to one hundred thousand characters
How to Handle:
A single pass linear scan ensures the solution runs in optimal O(n) time complexity and passes within time limits.
String contains leading zeros
How to Handle:
Leading zeros are processed normally as part of the string digits and mutated if their mapped value is larger.
0/257 completed