KatInterview

249. Group Shifted Strings

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to group strings that belong to the same "shifting sequence". A string s2 is in the same shifting sequence as s1 if s2 can be obtained by cyclically shifting every character of s1 by the same amount. For example, "bcd" is a shift of "abc" (each letter shifted by 1), and "yza" is a shift of "xyz". All strings within such a sequence must have the same length and the same pattern of relative differences between consecutive characters.

Solution

Group Shifted Strings in Python

import collections

class Solution:
    def groupStrings(self, strings: List[str]) -> List[List[str]]:
        # Use a defaultdict to group strings. The key is the canonical representation
        # of a shifting sequence.
        groups = collections.defaultdict(list)

        for s in strings:
            # Generate the canonical key for the string s.
            # The canonical form is the string shifted so that it starts with 'a'.
            if not s:
                key = ""
            else:
                # Calculate the offset needed to shift the first character to 'a'.
                offset = ord(s[0]) - ord('a')
                key_chars = []
                for char in s:
                    # Apply the shift to each character.
                    # Python's % operator handles negative numbers correctly for this purpose.
                    shifted_char_code = (ord(char) - offset - ord('a')) % 26 + ord('a')
                    key_chars.append(chr(shifted_char_code))
                key = "".join(key_chars)
            
            # Add the current string to its group.
            groups[key].append(s)

        # The values of the dictionary are the grouped strings.
        return list(groups.values())

Group Shifted Strings in Java

class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        // Use a HashMap to group strings. The key is the canonical representation
        // of a shifting sequence, and the value is a list of strings in that sequence.
        Map<String, List<String>> groups = new HashMap<>();

        for (String s : strings) {
            String key = getCanonicalKey(s);
            // If the key is not present, create a new list for it.
            groups.putIfAbsent(key, new ArrayList<>());
            // Add the current string to its group.
            groups.get(key).add(s);
        }

        // The values of the map are the grouped strings.
        // Return them as a new List.
        return new ArrayList<>(groups.values());
    }

    // Function to generate a canonical key for a string.
    // The canonical form is the string shifted so that it starts with 'a'.
    private String getCanonicalKey(String s) {
        if (s.isEmpty()) {
            return "";
        }

        char[] chars = s.toCharArray();
        // Calculate the offset needed to shift the first character to 'a'.
        int offset = chars[0] - 'a';

        for (int i = 0; i < chars.length; i++) {
            // Apply the shift to each character.
            // Add 26 before taking modulo to handle negative results from subtraction.
            int shiftedCharVal = (chars[i] - 'a' - offset + 26) % 26;
            chars[i] = (char) ('a' + shiftedCharVal);
        }

        return new String(chars);
    }
}

Group Shifted Strings in C++

class Solution {
public:
    vector<vector<string>> groupStrings(vector<string>& strings) {
        // Use a hash map to group strings. The key is the canonical representation
        // of a shifting sequence, and the value is a list of strings in that sequence.
        unordered_map<string, vector<string>> groups;

        for (const string& s : strings) {
            groups[getCanonicalKey(s)].push_back(s);
        }

        // Collect the grouped strings from the map into the result vector.
        vector<vector<string>> result;
        for (auto const& [key, val] : groups) {
            result.push_back(val);
        }

        return result;
    }

private:
    // Function to generate a canonical key for a string.
    // The canonical form is the string shifted so that it starts with 'a'.
    string getCanonicalKey(const string& s) {
        if (s.empty()) {
            return "";
        }

        string key = s;
        // Calculate the offset needed to shift the first character to 'a'.
        int offset = s[0] - 'a';

        for (char& c : key) {
            // Apply the shift to each character.
            // Add 26 before taking modulo to handle negative results correctly.
            int shifted_char_val = (c - 'a' - offset + 26) % 26;
            c = 'a' + shifted_char_val;
        }

        return key;
    }
};

Group Shifted Strings in TypeScript

function groupStrings(strings: string[]): string[][] {
    // Use a Map to group strings. The key is the canonical representation
    // of a shifting sequence, and the value is an array of strings in that sequence.
    const groups: Map<string, string[]> = new Map();

    for (const s of strings) {
        const key = getCanonicalKey(s);
        if (!groups.has(key)) {
            groups.set(key, []);
        }
        groups.get(key)!.push(s);
    }

    // The values of the map are the grouped strings.
    // Return them as a new array of arrays.
    return Array.from(groups.values());
}

// Function to generate a canonical key for a string.
// The canonical form is the string shifted so that it starts with 'a'.
function getCanonicalKey(s: string): string {
    if (s.length === 0) {
        return "";
    }

    // Calculate the offset needed to shift the first character to 'a'.
    const offset = s.charCodeAt(0) - 'a'.charCodeAt(0);
    let key = "";

    for (let i = 0; i < s.length; i++) {
        // Apply the shift to each character.
        // Add 26 before taking modulo to handle negative results from subtraction.
        const charCode = s.charCodeAt(i);
        const shiftedCharCode = (charCode - 'a'.charCodeAt(0) - offset + 26) % 26;
        key += String.fromCharCode('a'.charCodeAt(0) + shiftedCharCode);
    }

    return key;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.