Skip to main content
Back to problems
#848
Medium Algorithms

Shifting letters

Array String Prefix Sum
46.1% acceptance
Feb 22, 2026
1547
142
You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'. Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times. Return the final string after all such shifts to s are applied.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
/*
 * You are given a string s of lowercase English letters and an integer array shifts of the same length.
 * Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').
 * For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.
 * Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.
 * Return the final string after all such shifts to s are applied.
 * Example 1:
 * Input: s = "abc", shifts = [3,5,9]
 * Output: "rpl"
 * Explanation: We start with "abc".
 * After shifting the first 1 letters of s by 3, we have "dbc".
 * After shifting the first 2 letters of s by 5, we have "igc".
 * After shifting the first 3 letters of s by 9, we have "rpl", the answer.
 * Example 2:
 * Input: s = "aaa", shifts = [1,2,3]
 * Output: "gfd"
 * Constraints:
 * 1 <= s.length <= 105
 * s consists of lowercase English letters.
 * shifts.length == s.length
 * 0 <= shifts[i] <= 109
 */

impl Solution {
  pub fn shifting_letters(s: String, shifts: Vec<i32>) -> String {
    let mut bytes: Vec<u8> = s.into_bytes();
    let n = bytes.len();
    // suffix sum of shifts
    let mut total: i64 = 0;
    for i in (0..n).rev() {
      total = (total + shifts[i] as i64) % 26;
      bytes[i] = ((bytes[i] - b'a') as i64 + total).rem_euclid(26) as u8 + b'a';
    }
    String::from_utf8(bytes).unwrap()
  }
}