#2844
Medium Algorithms Minimum operations to make a special number
Math String Greedy Enumeration
38.5% acceptance
Feb 25, 2026
373
57
You are given a 0-indexed string num representing a non-negative integer.
In one operation, you can pick any digit of num and delete it. Note that if you delete all the digits of num, num becomes 0.
Return the minimum number of operations required to make num special.
An integer x is considered special if it is divisible by 25.
Solution
Rust
Time O(n³)
Space O(1)
impl Solution {
pub fn minimum_operations(num: String) -> i32 {
let b = num.as_bytes();
let n = b.len();
// Divisible by 25: last two digits in {00,25,50,75}
let endings: &[(u8, u8)] = &[(b'0', b'0'), (b'2', b'5'), (b'5', b'0'), (b'7', b'5')];
// Keep a single '0' anywhere => result is 0 (divisible by 25)
// Cost = delete everything except that one '0' = n - 1 (if any '0' exists)
let has_zero = b.iter().any(|&c| c == b'0');
let mut ans = if has_zero { n as i32 - 1 } else { n as i32 }; // n => delete all => 0
for &(d2, d1) in endings {
// find rightmost d1, then rightmost d2 before it
let mut j = n;
loop {
if j == 0 { break; }
j -= 1;
if b[j] == d1 {
// deletions after j
let del_right = (n - 1 - j) as i32;
// find d2 to the left of j
let mut i = j;
loop {
if i == 0 { break; }
i -= 1;
if b[i] == d2 {
let del_mid = (j - 1 - i) as i32;
ans = ans.min(del_right + del_mid);
break;
}
}
break;
}
}
}
ans
}
}