No Prefix Set

  • + 0 comments

    from typing import List

    class TrieNode: def init(self): self.children = {} self.is_end_of_word = False

    class Trie: def init(self): self.root = TrieNode()

    def insert_and_check(self, word: str) -> bool:
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
            if node.is_end_of_word:  # Current node is end of another word
                return False
        node.is_end_of_word = True
        if node.children:  # Current word is a prefix of another word
            return False
        return True
    
    def check_prefix(self, word: str) -> bool:
        node = self.root
        for char in word:
            if char not in node.children:
                return False
            node = node.children[char]
        return True
    

    def noPrefix(words: List[str]) -> None: trie = Trie()

    for word in words:
        if trie.check_prefix(word):
            print("BAD SET\n" + word)
            return
        if not trie.insert_and_check(word):
            print("BAD SET\n" + word)
            return
    
    print("GOOD SET")