Largest Number After Mutating Substring - 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. 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.

Input & Output

Example 1 — Basic Transformation
$ Input: num = "132", change = [9,8,5,0,2,6,7,1,4,3]
Output: "855"
💡 Note: Start at position 0: 1→8 (improvement), continue: 3→5 (improvement), 2→5 (improvement). Result: "855"
Example 2 — No Improvement Possible
$ Input: num = "132", change = [9,8,5,0,2,6,7,1,4,3]
Output: "832"
💡 Note: Start at position 0: 1→8 (improvement), then 3→0 would decrease so we stop. Result: "832"
Example 3 — Partial Transformation
$ Input: num = "5", change = [1,4,7,5,2,6,9,3,0,8]
Output: "5"
💡 Note: 5→2 would make it smaller, so no transformation gives the best result

Constraints

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

Visualization

Tap to expand
Largest Number After Mutating Substring INPUT num = "132" 1 idx 0 3 idx 1 2 idx 2 change[] array: 0 9 1 8 2 5 3 0 4 2 5 6 6 7 7 1 8 4 9 3 Digit d maps to change[d] Relevant Mappings: 1 --> 8 (larger!) 3 --> 0 (smaller) 2 --> 5 (larger!) ALGORITHM STEPS 1 Find Start Position Scan for change[d] > d 1: change[1]=8 > 1 OK 2 Start Mutation Begin mutating substring Mutate: 1 --> 8 3 Continue While Beneficial Keep going if change[d] >= d 3: change[3]=0 < 3 STOP 4 Mutate Remaining Continue checking rest 2: change[2]=5 > 2 OK Mutation Process: "132" --> "832" --> "855" (skip 3, mutate 2) FINAL RESULT Original: 1 3 2 Mutated: 8 5 5 Output: "855" OK - Largest Possible! 855 > 132 Key Insight: The greedy approach works because we want to maximize the leftmost digits first. 1. Start mutating when change[d] > d (makes the number larger) 2. Stop when change[d] < d (would make it smaller) - can't resume mutation after stopping TutorialsPoint - Largest Number After Mutating Substring | Greedy Approach
Asked in
Google 25 Amazon 20 Microsoft 15
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen