KatInterview

749. Shortest Completing Word

EasySolutions 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 the shortest word from a given list (words) that contains all the letters present in a licensePlate string. There are a few key rules to follow:

Solution

Shortest Completing Word in Python

from collections import Counter

class Solution:
    def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
        # Step 1: Create frequency map for the license plate letters.
        # We filter for letters, convert to lower case, and count them.
        plate_counter = Counter(c.lower() for c in licensePlate if c.isalpha())

        shortest_word = None

        # Step 2: Iterate through each word in the list.
        for word in words:
            # Optimization: if current word is not shorter than the best result, skip.
            # This also handles the tie-breaking rule (first one in the list).
            if shortest_word is not None and len(word) >= len(shortest_word):
                continue

            # Step 3: Check if the current word is a completing word.
            word_counter = Counter(word)
            
            is_completing = True
            # For each required letter and its count from the license plate...
            for char, count in plate_counter.items():
                # ...check if the word's counter has at least that many.
                if word_counter[char] < count:
                    is_completing = False
                    break
            
            # Step 4: If it's a completing word, update the result.
            if is_completing:
                shortest_word = word
        
        return shortest_word

Shortest Completing Word in Java

class Solution {
    public String shortestCompletingWord(String licensePlate, String[] words) {
        // Step 1: Create frequency map for the license plate letters.
        int[] plateFreq = getFrequencyMap(licensePlate);

        String result = null;

        // Step 2: Iterate through each word in the list.
        for (String word : words) {
            // Optimization: skip if word is not shorter than current best result.
            // This also handles the tie-breaking rule (first one in the list).
            if (result != null && word.length() >= result.length()) {
                continue;
            }

            // Step 3: Check if the current word is a completing word.
            int[] wordFreq = getFrequencyMap(word);
            if (isCompleting(wordFreq, plateFreq)) {
                // Step 4: If it is, update the result.
                // Because of the optimization, this is either the first completing
                // word found or a new shorter one.
                result = word;
            }
        }
        
        return result;
    }

    // Helper method to create a frequency map for a string.
    private int[] getFrequencyMap(String s) {
        int[] freq = new int[26];
        for (char c : s.toCharArray()) {
            if (Character.isLetter(c)) {
                freq[Character.toLowerCase(c) - 'a']++;
            }
        }
        return freq;
    }

    // Helper method to check if a word is completing.
    private boolean isCompleting(int[] wordFreq, int[] plateFreq) {
        for (int i = 0; i < 26; i++) {
            if (wordFreq[i] < plateFreq[i]) {
                return false;
            }
        }
        return true;
    }
}

Shortest Completing Word in C++

class Solution {
public:
    string shortestCompletingWord(string licensePlate, vector<string>& words) {
        // Step 1: Create frequency map for the license plate letters.
        // An array of 26 integers is used for 'a' through 'z'.
        vector<int> plateFreq(26, 0);
        for (char c : licensePlate) {
            if (isalpha(c)) {
                plateFreq[tolower(c) - 'a']++;
            }
        }

        string result = "";

        // Step 2: Iterate through each word in the list.
        for (const string& word : words) {
            // Optimization: if current word is not shorter than the best result found so far, skip it.
            // This also handles the tie-breaking rule (first one in the list).
            if (!result.empty() && word.length() >= result.length()) {
                continue;
            }

            // Step 3: Check if the current word is a completing word.
            vector<int> wordFreq(26, 0);
            for (char c : word) {
                wordFreq[c - 'a']++;
            }

            bool isCompleting = true;
            for (int i = 0; i < 26; ++i) {
                // Check if the word has enough of each required letter.
                if (wordFreq[i] < plateFreq[i]) {
                    isCompleting = false;
                    break;
                }
            }

            // Step 4: If it's a completing word, update the result.
            // Because of the optimization, this new result is either the first
            // completing word found or a shorter one.
            if (isCompleting) {
                result = word;
            }
        }
        
        return result;
    }
};

Shortest Completing Word in TypeScript

function shortestCompletingWord(licensePlate: string, words: string[]): string {
    // Step 1: Create frequency map for the license plate letters.
    const plateFreq = new Array(26).fill(0);
    for (const char of licensePlate) {
        if (/[a-zA-Z]/.test(char)) {
            plateFreq[char.toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0)]++;
        }
    }

    let result: string | null = null;

    // Step 2: Iterate through each word in the list.
    for (const word of words) {
        // Optimization: if word is not shorter than current best result, skip.
        // This also handles the tie-breaking rule (first one in the list).
        if (result !== null && word.length >= result.length) {
            continue;
        }

        // Step 3: Check if the current word is a completing word.
        const wordFreq = new Array(26).fill(0);
        for (const char of word) { // words[i] consists of lower case English letters.
            wordFreq[char.charCodeAt(0) - 'a'.charCodeAt(0)]++;
        }
        
        let isCompleting = true;
        for (let i = 0; i < 26; i++) {
            if (wordFreq[i] < plateFreq[i]) {
                isCompleting = false;
                break;
            }
        }

        // Step 4: If it is, update the result.
        // Because of the optimization, this new result is either the first
        // completing word found or a shorter one.
        if (isCompleting) {
            result = word;
        }
    }

    // The problem guarantees an answer exists, so result will not be null.
    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.