No Prefix Set

  • + 0 comments

    C# solution using a Trie

    class TrieNode
    {
        public TrieNode[] Child = new TrieNode[10];
        public bool WordEnd = false;
    }
    
    class Trie
    {
        public TrieNode Root = new TrieNode();
        
        // Inserts s into the Trie and also checks if s is a prefix or has a prefix in the Trie.
        public bool Insert(string s)
        {
            bool hasPrefix = false;
            bool isPrefix = true;
            TrieNode currentNode = this.Root;
            
            foreach(char ch in s)
            {
                if (currentNode.WordEnd)
                {
                    hasPrefix = true;
                }
                
                int index = ch - 'a';
                
                if (currentNode.Child[index] == null)
                {
                    currentNode.Child[index] = new();
                    isPrefix = false;
                }
                
                currentNode = currentNode.Child[index];
            }
            
            currentNode.WordEnd = true;
            
            return hasPrefix || isPrefix;
        }
    }
    
    class Result
    {
        public static void noPrefix(List<string> words)
        {
            Trie trie = new();
            
            foreach (string word in words)
            {
                bool prefix = trie.Insert(word);
                
                if (prefix)
                {
                    Console.WriteLine("BAD SET");
                    Console.WriteLine(word);
                    return;
                }
            }
            
            Console.WriteLine("GOOD SET");
        }
    }