Longest Word in Dictionary LeetCode solution in Python
1# Runtime: 240 ms (Top 36.59%) | Memory: 15.2 MB (Top 46.59%)2class Solution:3def longestWord(self, words: List[str]) -> str:4TrieNode = lambda: defaultdict(TrieNode)5root = TrieNode()6for i, s in enumerate(words):7cur = root8for c in s:9cur = cur[c]10cur["$"] = i1112ans = ""13st = list(root.values())14while st:15cur = st.pop()16if "$" in cur:17w = words[cur["$"]]18if len(ans) < len(w) or len(ans) == len(w) and w < ans:19ans = w20st.extend([cur[i] for i in cur if i != "$"])21return ans