Group Shifted Strings Problem
Description
LeetCode Problem 249.
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.
Example 1:
Input: strings = ["abc","bcd","acef","xyz","az","ba","a","z"]
Output: [["acef"],["a","z"],["abc","bcd","xyz"],["az","ba"]]
Example 2:
Input: strings = ["a"]
Output: [["a"]]
Constraints:
1 <= strings.length <= 2001 <= strings[i].length <= 50strings[i]consists of lowercase English letters.
Solution
Approach: Hash Map of Normalized Strings
Shifting changes every letter by the same amount, so it never changes the gap between neighboring letters (counted mod 26). Two strings are in the same shifting sequence exactly when they have the same length and the same gaps.
An easy way to capture that is to give each string a key: shift it until its first letter is a. If s[0] is k letters after a, move every letter back by k, wrapping around: (c - 'a' - k) mod 26. For example "xyz", "bcd" and "abc" all become "abc", and "az" and "ba" both become "az".
Then group the strings in a hash map from key to list of strings, and return the lists.
The wrap-around is the tricky part: "ba" shifted back by one gives 'a' and then 'a' - 1, which must become 'z'. In languages where % can return a negative number, add 26 before taking the remainder.
Complexity: O(L) time and space, where L is the total length of all strings.
import collections
class Solution:
def groupStrings(self, strings: List[str]) -> List[List[str]]:
groups = collections.defaultdict(list) # key -> strings in that shifting sequence
for s in strings:
# Shift s so that it starts with 'a'; every string of the sequence gets the same key.
shift = ord(s[0]) - ord("a")
key = "".join(chr((ord(c) - ord("a") - shift) % 26 + ord("a")) for c in s)
groups[key].append(s)
return list(groups.values())