#1946
Medium Algorithms Largest number after mutating substring
Array String Greedy
37.9% acceptance
Feb 25, 2026
236
232
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn maximum_number(num: String, change: Vec<i32>) -> String {
let mut bytes: Vec<u8> = num.into_bytes();
let mut started = false;
for b in bytes.iter_mut() {
let d = (*b - b'0') as usize;
let mapped = change[d] as u8;
if mapped > d as u8 {
*b = b'0' + mapped;
started = true;
} else if mapped < d as u8 {
if started {
break;
}
}
// if equal, continue (don't break the substring)
}
String::from_utf8(bytes).unwrap()
}
}