Longest Word in Dictionary

Problem Summary

Key Observations

Approach Taken

Why This Works

Main Concepts Used

Time & Space Complexity

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

Common Mistakes / Things I Got Stuck On