KatInterview

527. Word Abbreviation

HardSolutions 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 find a unique abbreviation for each word in a given list of distinct words. The abbreviation rules are defined in three parts:

Solution

Word Abbreviation in Python

from collections import defaultdict

class Solution:
    def wordsAbbreviation(self, words: List[str]) -> List[str]:
        n = len(words)
        ans = ["" for _ in range(n)]
        # prefix[i] stores the current prefix length for words[i].
        prefix = [1] * n

        # Helper function to generate an abbreviation.
        def get_abbr(word, p):
            # If the abbreviation is not shorter, return the original word.
            if p + 2 >= len(word):
                return word
            # Construct abbreviation: prefix + number of middle chars + last char.
            return word[:p] + str(len(word) - 1 - p) + word[-1]

        # Initial abbreviation for all words with prefix length 1.
        for i in range(n):
            ans[i] = get_abbr(words[i], prefix[i])

        # Iteratively resolve conflicts.
        while True:
            # Group words by their current abbreviation.
            groups = defaultdict(list)
            for i, abbr in enumerate(ans):
                groups[abbr].append(i)
            
            conflict_found = False
            # Check for groups with more than one word (conflicts).
            for indices in groups.values():
                if len(indices) > 1:
                    conflict_found = True
                    # For each word in the conflict group, increase prefix and re-abbreviate.
                    for i in indices:
                        prefix[i] += 1
                        ans[i] = get_abbr(words[i], prefix[i])
            
            # If no conflicts were found in this pass, we are done.
            if not conflict_found:
                break
        
        return ans

Word Abbreviation in Java

class Solution {
    public List<String> wordsAbbreviation(List<String> words) {
        int n = words.size();
        String[] ans = new String[n];
        // prefix[i] stores the current prefix length for words[i].
        int[] prefix = new int[n];

        // Initial abbreviation for all words with prefix length 1.
        for (int i = 0; i < n; i++) {
            prefix[i] = 1;
            ans[i] = getAbbr(words.get(i), prefix[i]);
        }

        // Iteratively resolve conflicts.
        while (true) {
            // Group words by their current abbreviation.
            Map<String, List<Integer>> groups = new HashMap<>();
            for (int i = 0; i < n; i++) {
                groups.computeIfAbsent(ans[i], k -> new ArrayList<>()).add(i);
            }

            boolean conflictFound = false;
            // Check for groups with more than one word (conflicts).
            for (List<Integer> indices : groups.values()) {
                if (indices.size() > 1) {
                    conflictFound = true;
                    // For each word in the conflict group, increase prefix length and update abbreviation.
                    for (int i : indices) {
                        prefix[i]++;
                        ans[i] = getAbbr(words.get(i), prefix[i]);
                    }
                }
            }

            // If no conflicts were found in this pass, we are done.
            if (!conflictFound) {
                break;
            }
        }
        return Arrays.asList(ans);
    }
    
    // Helper function to generate an abbreviation for a word with a given prefix length.
    private String getAbbr(String word, int p) {
        int n = word.length();
        // If the abbreviation would not be shorter than the original word, return the word itself.
        if (p + 2 >= n) {
            return word;
        }
        // Construct abbreviation: prefix + number of middle chars + last char.
        String num = Integer.toString(n - p - 1);
        return word.substring(0, p) + num + word.charAt(n - 1);
    }
}

Word Abbreviation in C++

class Solution {
public:
    // Helper function to generate an abbreviation for a word with a given prefix length.
    string getAbbr(const string& word, int p) {
        int n = word.length();
        // If the abbreviation would not be shorter than the original word, return the word itself.
        // Condition: len(prefix) + len(number) + 1 < len(word)
        // A simple check is if len(word) is too short relative to prefix length.
        // If len(word) <= p + 2, the middle part has 1 or 0 chars.
        // e.g., word="apple", p=3. abbr="app1e" (len 5, same as word). not shorter.
        if (p + 2 >= n) {
            return word;
        }
        return word.substr(0, p) + to_string(n - p - 1) + word.back();
    }

    vector<string> wordsAbbreviation(vector<string>& words) {
        int n = words.size();
        vector<string> ans(n);
        // prefix[i] stores the current prefix length for words[i].
        vector<int> prefix(n, 1);

        // Initial abbreviation for all words with prefix length 1.
        for (int i = 0; i < n; ++i) {
            ans[i] = getAbbr(words[i], prefix[i]);
        }

        // Iteratively resolve conflicts.
        while (true) {
            // Group words by their current abbreviation.
            unordered_map<string, vector<int>> groups;
            for (int i = 0; i < n; ++i) {
                groups[ans[i]].push_back(i);
            }

            bool conflict_found = false;
            // Check for groups with more than one word (conflicts).
            for (auto const& [abbr, indices] : groups) {
                if (indices.size() > 1) {
                    conflict_found = true;
                    // For each word in the conflict group, increase prefix length and update abbreviation.
                    for (int i : indices) {
                        prefix[i]++;
                        ans[i] = getAbbr(words[i], prefix[i]);
                    }
                }
            }

            // If no conflicts were found in this pass, we are done.
            if (!conflict_found) {
                break;
            }
        }

        return ans;
    }
};

Word Abbreviation in TypeScript

function wordsAbbreviation(words: string[]): string[] {
    // Helper function to generate an abbreviation for a word with a given prefix length.
    const getAbbr = (word: string, p: number): string => {
        const n = word.length;
        // If the abbreviation would not be shorter than the original word, return the word itself.
        if (p + 2 >= n) {
            return word;
        }
        // Construct abbreviation: prefix + number of middle chars + last char.
        const num = n - 1 - p;
        return word.substring(0, p) + num.toString() + word[n - 1];
    };
    
    const n = words.length;
    const ans: string[] = new Array(n);
    // prefix[i] stores the current prefix length for words[i].
    const prefix: number[] = new Array(n).fill(1);

    // Initial abbreviation for all words with prefix length 1.
    for (let i = 0; i < n; i++) {
        ans[i] = getAbbr(words[i], prefix[i]);
    }

    // Iteratively resolve conflicts.
    while (true) {
        // Group words by their current abbreviation.
        const groups = new Map<string, number[]>();
        for (let i = 0; i < n; i++) {
            if (!groups.has(ans[i])) {
                groups.set(ans[i], []);
            }
            groups.get(ans[i])!.push(i);
        }

        let conflictFound = false;
        // Check for groups with more than one word (conflicts).
        for (const indices of groups.values()) {
            if (indices.length > 1) {
                conflictFound = true;
                // For each word in the conflict group, increase prefix length and update abbreviation.
                for (const i of indices) {
                    prefix[i]++;
                    ans[i] = getAbbr(words[i], prefix[i]);
                }
            }
        }
        
        // If no conflicts were found in this pass, we are done.
        if (!conflictFound) {
            break;
        }
    }
    
    return ans;
};

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.