KatInterview

320. Generalized Abbreviation

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 generate all "generalized abbreviations" of a given word. The definition specifies replacing non-overlapping and non-adjacent substrings with their lengths. For example, for word = "word", valid abbreviations include w2d (replacing or with 2), 1o1d (replacing w with 1 and r with 1), and 4 (replacing word with 4).

Solution

Generalized Abbreviation in Python

class Solution:
    def generateAbbreviations(self, word: str) -> List[str]:
        result = []

        def backtrack(index: int, current_abbr: str, count: int):
            # Base case: we have processed the entire word
            if index == len(word):
                # If there's a pending abbreviation count, append it
                if count > 0:
                    result.append(current_abbr + str(count))
                else:
                    result.append(current_abbr)
                return

            # Choice 1: Abbreviate the current character
            # We increment the count and move to the next character
            backtrack(index + 1, current_abbr, count + 1)

            # Choice 2: Keep the current character
            # First, if there's an ongoing abbreviation, append its count
            if count > 0:
                new_abbr = current_abbr + str(count) + word[index]
            else:
                new_abbr = current_abbr + word[index]
            
            # Move to the next character with the abbreviation count reset to 0
            backtrack(index + 1, new_abbr, 0)

        backtrack(0, "", 0)
        return result

Generalized Abbreviation in Java

class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> result = new ArrayList<>();
        backtrack(result, word, 0, new StringBuilder(), 0);
        return result;
    }

    private void backtrack(List<String> result, String word, int index, StringBuilder current_abbr, int count) {
        int len = current_abbr.length(); // Save current length for backtracking

        // Base case: we have processed the entire word
        if (index == word.length()) {
            // If there's a pending abbreviation count, append it
            if (count > 0) {
                current_abbr.append(count);
            }
            result.add(current_abbr.toString());
        } else {
            // Choice 1: Abbreviate the current character
            // We increment the count and move to the next character
            backtrack(result, word, index + 1, current_abbr, count + 1);

            // Choice 2: Keep the current character
            // First, if there's an ongoing abbreviation, append its count
            if (count > 0) {
                current_abbr.append(count);
            }
            // Then, append the current character
            current_abbr.append(word.charAt(index));
            // Move to the next character with the abbreviation count reset to 0
            backtrack(result, word, index + 1, current_abbr, 0);
        }

        // Backtrack by restoring the StringBuilder to its original state
        current_abbr.setLength(len);
    }
}

Generalized Abbreviation in C++

class Solution {
public:
    vector<string> generateAbbreviations(string word) {
        vector<string> result;
        backtrack(result, word, 0, "", 0);
        return result;
    }

private:
    void backtrack(vector<string>& result, const string& word, int index, string current_abbr, int count) {
        // Base case: we have processed the entire word
        if (index == word.length()) {
            // If there's a pending abbreviation count, append it
            if (count > 0) {
                current_abbr += to_string(count);
            }
            result.push_back(current_abbr);
            return;
        }

        // Choice 1: Abbreviate the current character
        // We increment the count and move to the next character
        backtrack(result, word, index + 1, current_abbr, count + 1);

        // Choice 2: Keep the current character
        // First, if there's an ongoing abbreviation, append its count to the string
        if (count > 0) {
            current_abbr += to_string(count);
        }
        // Then, append the current character
        current_abbr += word[index];
        // Move to the next character with the abbreviation count reset to 0
        backtrack(result, word, index + 1, current_abbr, 0);
    }
};

Generalized Abbreviation in TypeScript

function generateAbbreviations(word: string): string[] {
    const result: string[] = [];

    function backtrack(index: number, current_abbr: string, count: number): void {
        // Base case: we have processed the entire word
        if (index === word.length) {
            // If there's a pending abbreviation count, append it
            if (count > 0) {
                result.push(current_abbr + count);
            } else {
                result.push(current_abbr);
            }
            return;
        }

        // Choice 1: Abbreviate the current character
        // We increment the count and move to the next character
        backtrack(index + 1, current_abbr, count + 1);

        // Choice 2: Keep the current character
        let new_abbr = current_abbr;
        // First, if there's an ongoing abbreviation, append its count
        if (count > 0) {
            new_abbr += count;
        }
        // Then, append the current character
        new_abbr += word[index];
        
        // Move to the next character with the abbreviation count reset to 0
        backtrack(index + 1, new_abbr, 0);
    }

    backtrack(0, "", 0);
    return result;
};

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.