Group Shifted Strings

medium hash map string

Problem

Two strings are in the same shift sequence if one can be obtained from the other by shifting each character. Group strings that belong to the same shift sequence.

Input["abc","bcd","acef","xyz","az","ba","a","z"]
Output[["a","z"],["abc","bcd","xyz"],["acef"],["az","ba"]]
"abc" and "bcd" share gaps [1,1]; "az" and "ba" share gap [1].

def group_strings(strs):
    groups = {}
    for s in strs:
        key = tuple((ord(s[i+1]) - ord(s[i])) % 26 for i in range(len(s) - 1))
        groups.setdefault(key, []).append(s)
    return list(groups.values())
function groupStrings(strs) {
  const m = new Map();
  for (const s of strs) {
    const key = [];
    for (let i = 0; i + 1 < s.length; i++) {
      key.push(((s.charCodeAt(i+1) - s.charCodeAt(i)) % 26 + 26) % 26);
    }
    const k = key.join(",");
    if (!m.has(k)) m.set(k, []);
    m.get(k).push(s);
  }
  return [...m.values()];
}
class Solution {
    public List> groupStrings(String[] strs) {
        Map> m = new HashMap<>();
        for (String s : strs) {
            StringBuilder key = new StringBuilder();
            for (int i = 0; i + 1 < s.length(); i++) {
                key.append((s.charAt(i+1) - s.charAt(i) + 26) % 26).append(',');
            }
            m.computeIfAbsent(key.toString(), k -> new ArrayList<>()).add(s);
        }
        return new ArrayList<>(m.values());
    }
}
vector> groupStrings(vector& strs) {
    unordered_map> m;
    for (auto& s : strs) {
        string key;
        for (int i = 0; i + 1 < (int)s.size(); i++) {
            int d = ((s[i+1] - s[i]) % 26 + 26) % 26;
            key += to_string(d) + ",";
        }
        m[key].push_back(s);
    }
    vector> out;
    for (auto& [_, v] : m) out.push_back(v);
    return out;
}
Time: O(N · L) Space: O(N · L)