We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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
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")
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
No Prefix Set
You are viewing a single comment's thread. Return to all 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 noPrefix(words: List[str]) -> None: trie = Trie()