#1946

Largest Number After Mutating Substring

Medium
ArrayStringGreedyGreedyArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach involves iterating through the string once while deciding when to start and stop mutating the substring. We only mutate when the new digit is greater than the original, and we stop when we encounter a digit that is not beneficial to change.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a result string to build the final number.
  2. 2Step 2: Iterate through each digit of the num string.
  3. 3Step 3: If the current digit can be changed to a larger digit, start mutating until the digit is smaller than the original or the end of the string is reached.
  4. 4Step 4: Append either the mutated digit or the original digit to the result.
solution.py15 lines
1# Full working Python code
2
3def largestNumberAfterMutatingSubstring(num: str, change: list) -> str:
4    result = []
5    mutating = False
6    for digit in num:
7        d = int(digit)
8        if change[d] > d:
9            mutating = True
10            result.append(str(change[d]))
11        elif change[d] < d and mutating:
12            break
13        else:
14            result.append(digit)
15    return ''.join(result) + num[len(result):]

Complexity note: The time complexity is O(n) because we only make a single pass through the string. The space complexity is O(n) due to the result string that we build.

  • 1Changing digits only when the new digit is larger is crucial for maximizing the number.
  • 2Once we start mutating, we should stop as soon as we encounter a digit that cannot be improved.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.