Skip to main content
Back to problems
#3675
Medium Algorithms

Minimum operations to transform string

String Greedy
61.9% acceptance
Feb 25, 2026
74
7
You are given a string s consisting only of lowercase English letters. You can perform the following operation any number of times (including zero): Choose any character c in the string and replace every occurrence of c with the next lowercase letter in the English alphabet. Return the minimum number of operations required to transform s into a string consisting of only 'a' characters. Note: Consider the alphabet as circular, thus 'a' comes after 'z'.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(s: String) -> i32 {
    // Each operation shifts a chosen character forward by 1 (circularly: z -> a).
    // To transform s to all 'a', each character must travel forward until it reaches 'a'.
    // Forward distance from char c to 'a': (26 - (c - 'a')) % 26
    //   e.g. 'a'->0, 'z'->1, 'y'->2, 'b'->25
    // Key insight: we can always merge a closer character into a farther one by letting
    // the farther char "catch up" to the closer one along the way, then they travel
    // together. So the minimum ops equals the maximum forward distance among all chars.
    s.bytes()
      .map(|b| (26 - (b - b'a') as i32) % 26)
      .max()
      .unwrap_or(0)
  }
}