Largest Number After Mutating Substring — LeetCode 1946 Python Solution
- Problem
- #1946
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- num = "132", change = [9,8,5,0,3,6,4,2,6,8]
- Output
- "832"
- Explanation
- Replace the substring "1":
Python solution
class Solution:
def maximumNumber(self, num: str, change: List[int]) -> str:
s = list(num)
changed = False
for i, c in enumerate(s):
d = str(change[int(c)])
if changed and d < c:
break
if d > c:
changed = True
s[i] = d
return "".join(s)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1946. Largest Number After Mutating Substring is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1946. Largest Number After Mutating Substring?
- LeetCode 1946. Largest Number After Mutating Substring is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1946. Largest Number After Mutating Substring?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1946. Largest Number After Mutating Substring?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1946. Largest Number After Mutating Substring cover?
- LeetCode 1946. Largest Number After Mutating Substring is tagged Greedy, Array and String on LeetCode.