Skip to main content
Back to problems
#1427
Easy Algorithms

Perform string shifts

Array Math String
56.0% acceptance
Mar 31, 2026
276
16
You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [directioni, amounti]: directioni can be 0 (for left shift) or 1 (for right shift). amounti is the amount by which string s is to be shifted. A left shift by 1 means remove the first character of s and append it to the end. Similarly, a right shift by 1 means remove the last character of s and add it to the beginning. Return the final string after all operations.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn string_shift(s: String, shift: Vec<Vec<i32>>) -> String {
    let len = s.len() as i32;
    let net: i32 = shift.iter().map(|op| if op[0] == 0 { -op[1] } else { op[1] }).sum();
    let net = ((net % len) + len) % len;
    let split = ((len - net) % len) as usize;
    let mut result = String::with_capacity(s.len());
    result.push_str(&s[split..]);
    result.push_str(&s[..split]);
    result
  }
}