Skip to main content
Back to problems
#3335
Medium Algorithms

Total characters in string after transformations i

Hash Table Math String Dynamic Programming Counting
45.7% acceptance
Feb 23, 2026
612
46
You are given a string s and an integer t, representing the number of transformations to perform. In one transformation, every character in s is replaced according to the following rules: If the character is 'z', replace it with the string "ab". Otherwise, replace it with the next character in the alphabet. For example, 'a' is replaced with 'b', 'b' is replaced with 'c', and so on. Return the length of the resulting string after exactly t transformations. Since the answer may be very large, return it modulo 109 + 7.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn length_after_transformations(s: String, t: i32) -> i32 {
    const MOD: u64 = 1_000_000_007;
    // Count frequency of each char
    let mut cnt = [0u64; 26];
    for b in s.bytes() { cnt[(b - b'a') as usize] += 1; }
    
    for _ in 0..t {
      let mut next = [0u64; 26];
      for i in 0..25 {
        next[i + 1] = (next[i + 1] + cnt[i]) % MOD;
      }
      // 'z' -> "ab"
      next[0] = (next[0] + cnt[25]) % MOD;
      next[1] = (next[1] + cnt[25]) % MOD;
      cnt = next;
    }
    
    (cnt.iter().sum::<u64>() % MOD) as i32
  }
}