Skip to main content
Back to problems
#249
Medium Algorithms

Group shifted strings

Array Hash Table String
67.8% acceptance
Mar 31, 2026
1785
446
Perform the following shift operations on a string: Right shift: Replace every letter with the successive letter of the English alphabet, where 'z' is replaced by 'a'. For example, "abc" can be right-shifted to "bcd" or "xyz" can be right-shifted to "yza". Left shift: Replace every letter with the preceding letter of the English alphabet, where 'a' is replaced by 'z'. For example, "bcd" can be left-shifted to "abc" or "yza" can be left-shifted to "xyz". We can keep shifting the string in both directions to form an endless shifting sequence. For example, shift "abc" to form the sequence: ... <-> "abc" <-> "bcd" <-> ... <-> "xyz" <-> "yza" <-> .... <-> "zab" <-> "abc" <-> ... You are given an array of strings strings, group together all strings[i] that belong to the same shifting sequence. You may return the answer in any order.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn group_strings(strings: Vec<String>) -> Vec<Vec<String>> {
    use std::collections::HashMap;
    let mut map: HashMap<Vec<i32>, Vec<String>> = HashMap::new();
    for s in strings {
      let bytes: Vec<u8> = s.bytes().collect();
      let key: Vec<i32> = bytes.windows(2)
        .map(|w| ((w[1] as i32 - w[0] as i32 + 26) % 26))
        .collect();
      map.entry(key).or_default().push(s);
    }
    map.into_values().collect()
  }
}