Wednesday, July 24, 2024

[LeetCode] Shortest Completing Word

Problem: Given a string licensePlate and an array of strings words, find the shortest completing word in words.

A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.

For example, if licensePlate = "aBc 12c", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are "abccdef", "caaacab", and "cbca".

Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.

Example:

Input: licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"]
Output: "steps"
Explanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step" contains 't' and 'p', but only contains 1 's'.
"steps" contains 't', 'p', and both 's' characters.
"stripe" is missing an 's'.
"stepple" is missing an 's'.
Since "steps" is the only word containing all the letters, that is the answer.
Input: licensePlate = "1s3 456", words = ["looks","pest","stew","show"]
Output: "pest"
Explanation: licensePlate only contains the letter 's'. All the words contain 's', but among these "pest", "stew", and "show" are shortest. The answer is "pest" because it is the word that appears earliest of the 3.


Approach: This is a simple problem to solve. We can easily solve it using using two hash maps. Directly look at the implementation to understand the approach.


Implementation in C#:

    public string ShortestCompletingWord(string licensePlate, string[] words)
    {
        var plateCharsMap = new int[26];
        foreach(char ch in licensePlate)
        {
            if (Char.IsLetter(ch))
            {
                ++plateCharsMap[Char.ToLower(ch) - 'a'];
            }
        }
        string result = null;
        foreach (string word in words)
        {
            int length = word.Length;
            var wordCharMap = new int[26];
            foreach (char ch in word)
            {
                ++wordCharMap[ch - 'a'];
            }
            if (this.IsCompleteWord(plateCharsMap, wordCharMap))
            {
                if (result == null || length < result.Length)
                {
                    result = word;
                }
            }
        }
        return result;
    }

    private bool IsCompleteWord(int[] plateCharsMap, int[] wordCharMap)
    {
        for (int i = 0; i < 26; ++i)
        {
            if (plateCharsMap[i] > wordCharMap[i])
            {
                return false;
            }
        }
        return true;
    }


Complexity: O(m*n) where m is number of words and n is length of largest word.

No comments:

Post a Comment