No Prefix Set

  • + 0 comments
    class Node:
        def __init__(self):
            self.char = {}
            self.is_end = False
    
    class Trie:
        def __init__(self):
            self.root = Node()
            
        def insert(self, word: str) -> bool:
            # Return True if inserted; False if word is a prefix or has a prefix
            curr_node = self.root
            for c in word:
                if c not in curr_node.char:
                    curr_node.char[c] = Node()
                curr_node = curr_node.char[c]
                if curr_node.is_end:
                    # An existing word is a prefix of the current word
                    return False
            if curr_node.char:
                # The current word is a prefix of an existing word
                return False
            curr_node.is_end = True
            # The word was successfully inserted
            return True
    
    def noPrefix(words: list[str]) -> None:
        trie = Trie()
        for word in words:
            if not trie.insert(word):
                print('BAD SET')
                print(word)
                return
        print('GOOD SET')