Trie Variation

Here is the problem: https://leetcode.com/problems/search-suggestions-system/
1268. Search Suggestions System
Medium
Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return list of lists of the suggested products after each character of searchWord is typed. 

Example 1:
Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [
["mobile","moneypot","monitor"],
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"],
["mouse","mousepad"]
]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]
After typing mou, mous and mouse the system suggests ["mouse","mousepad"]
Example 2:
Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
Example 3:
Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]
Example 4:
Input: products = ["havana"], searchWord = "tatiana"
Output: [[],[],[],[],[],[],[]]

Constraints:
  • 1 <= products.length <= 1000
  • There are no repeated elements in products.
  • 1 <= Σ products[i].length <= 2 * 10^4
  • All characters of products[i] are lower-case English letters.
  • 1 <= searchWord.length <= 1000
  • All characters of searchWord are lower-case English letters.
Trie fits well for this problem, with a simple variation: the keys should be sorted. Hence instead of using a simple Hash Map to stored the nodes of the trie, change it to a Sorted Dictionary. The main implementation is here where the key is to systematically cover all the base cases, and the induction will leverage the fact that keys are sorted which will generate the desired lexicographic order, this is the for loop that does so. Slow, but enough to pass. Cheers, ACC.

public class Trie
{
    private SortedDictionary<char, Trie> sd = null;
    private bool endOfWord = false;
    public Trie()
    {
        sd = new SortedDictionary<char, Trie>();
        endOfWord = false;
    }

    public void Insert(string word)
    {
        if (String.IsNullOrEmpty(word)) this.endOfWord = true;
        else if (sd.ContainsKey(word[0])) (sd[word[0]]).Insert(word.Substring(1));
        else
        {
            Trie newTrie = new Trie();
            sd.Add(word[0], newTrie);
            (sd[word[0]]).Insert(word.Substring(1));
        }
    }

    public void SearchMaxMatches(string searchWord,
                                    string currentWord,
                                    int MAX,
                                    ref int numberMatches,
                                    List<string> matches)
    {
        if (numberMatches >= MAX) return;
        if (!String.IsNullOrEmpty(searchWord) && !sd.ContainsKey(searchWord[0])) return;
        if (!String.IsNullOrEmpty(searchWord) && sd.ContainsKey(searchWord[0]))
        {
            sd[searchWord[0]].SearchMaxMatches(searchWord.Substring(1), currentWord + searchWord[0].ToString(), MAX, ref numberMatches, matches);
            return;
        }

        //Searchword is empty
        if (endOfWord)
        {
            matches.Add(currentWord);
            numberMatches++;
        }
        foreach (char key in sd.Keys)
        {
            sd[key].SearchMaxMatches(searchWord, currentWord + key.ToString(), MAX, ref numberMatches, matches);
        }
    }
}

public class Solution
{
    public IList<IList<string>> SuggestedProducts(string[] products, string searchWord)
    {
        Trie trie = new Trie();
        foreach (string product in products) trie.Insert(product);

        List<IList<string>> retVal = new List<IList<string>>();
        for (int i = 1; i <= searchWord.Length; i++)
        {
            List<string> matches = new List<string>();
            int numberMatches = 0;
            trie.SearchMaxMatches(searchWord.Substring(0, i), "", 3, ref numberMatches, matches);
            retVal.Add(matches);
        }

        return retVal;
    }
}

Comments

Popular posts from this blog

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons