#1702
Medium Algorithms Maximum binary string after change
String Greedy
48.0% acceptance
Feb 25, 2026
528
64
You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times:
Operation 1: If the number contains the substring "00", you can replace it with "10".
For example, "00010" -> "10010"
Operation 2: If the number contains the substring "10", you can replace it with "01".
For example, "00010" -> "00001"
Return the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn maximum_binary_string(binary: String) -> String {
let bytes = binary.as_bytes();
let n = bytes.len();
let first_zero = match bytes.iter().position(|&b| b == b'0') {
Some(p) => p,
None => return binary,
};
let zeros: usize = bytes[first_zero..].iter().filter(|&&b| b == b'0').count();
if zeros == 0 { return binary; }
let mut result = vec![b'1'; n];
result[first_zero + zeros - 1] = b'0';
String::from_utf8(result).unwrap()
}
}