Time: → Reason: Sorting is dominant since that depends on number of words and average length of the word
Space: → Reason: Worst case, we store all characters from words
Code
class TrieNode:
def __init__(self):
self.children = {}
class Solution:
def __init__(self):
self.root = TrieNode()
def longestWord(self, words: List[str]) -> str:
words.sort() # ['a', 'ap', 'app', 'appl', 'apple', 'apply', 'b', 'ban', 'banana']
lengthOflongestWord = 0
longestWord = ""
# build a prefix tree
# TrieNode doenst exist we create and check current length with max length, and save word
# {}
# \
# a: {} b
# \
# p: {}
#. \
#. p: {}
# \
# l
# \
# e
for word in words:
cur = self.root
for i, c in enumerate(word): # 1, p
if c not in cur.children and i != len(word) - 1:
break
if c not in cur.children:
cur.children[c] = TrieNode()
currentLevel = i + 1
if currentLevel > lengthOflongestWord:
lengthOflongestWord = currentLevel
longestWord = word[:currentLevel]
break
cur = cur.children[c]
return longestWord