KatInterview

720. Longest Word in Dictionary

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the longest word from a given dictionary (words) that can be constructed by adding one character at a time, using other words from the same dictionary. This means for a word to be a valid candidate, all of its prefixes must also exist in the words list. For instance, for "apple" to be a valid candidate, "a", "ap", "app", and "appl" must all be present in the dictionary. If there are multiple longest words, we should return the one that is lexicographically smallest.

Solution

Longest Word in Dictionary in Python

class Solution:
    def longestWord(self, words: list[str]) -> str:
        # Using a dictionary to implement the Trie
        trie = {}
        for word in words:
            node = trie
            for char in word:
                # setdefault returns the value if key exists, otherwise inserts key with a value of {} and returns {}
                node = node.setdefault(char, {})
            # Mark the end of a word by storing the word itself
            node['#'] = word

        self.result = ""

        def dfs(node):
            # The root itself does not represent a word, so its children are the starting points.
            # A path can only be extended if the child node represents a complete word.
            for key in node:
                if key == '#':
                    continue
                
                child_node = node[key]
                if '#' in child_node:
                    candidate = child_node['#']
                    # Check if the candidate is a better answer
                    if len(candidate) > len(self.result):
                        self.result = candidate
                    elif len(candidate) == len(self.result) and candidate < self.result:
                        self.result = candidate
                    
                    # Continue the search from this valid buildable word
                    dfs(child_node)
        
        dfs(trie)
        return self.result

Longest Word in Dictionary in Java

class Solution {
    // TrieNode class for the prefix tree
    class TrieNode {
        TrieNode[] children = new TrieNode[26];
        String word; // Store the full word at the end node
    }

    private String result = "";

    public String longestWord(String[] words) {
        TrieNode root = new TrieNode();
        // Build the Trie
        for (String word : words) {
            TrieNode node = root;
            for (char c : word.toCharArray()) {
                int i = c - 'a';
                if (node.children[i] == null) {
                    node.children[i] = new TrieNode();
                }
                node = node.children[i];
            }
            node.word = word;
        }

        // Perform DFS to find the longest buildable word
        dfs(root);
        return result;
    }

    private void dfs(TrieNode node) {
        // Base case is handled by the loop condition. 
        // We explore from the root, and only proceed down paths where nodes represent complete words.
        for (TrieNode child : node.children) {
            if (child != null && child.word != null) {
                // A candidate is found
                String candidate = child.word;
                // Update result if it's a better answer
                if (candidate.length() > result.length()) {
                    result = candidate;
                } else if (candidate.length() == result.length() && candidate.compareTo(result) < 0) {
                    result = candidate;
                }

                // Continue searching from this valid word node
                dfs(child);
            }
        }
    }
}

Longest Word in Dictionary in C++

class Solution {
private:
    // TrieNode structure for the prefix tree
    struct TrieNode {
        TrieNode* children[26];
        string word; // Store the full word at the end node

        TrieNode() : word("") {
            for (int i = 0; i < 26; ++i) {
                children[i] = nullptr;
            }
        }
    };

    TrieNode* root;
    string result;

    // Insert a word into the Trie
    void insert(const string& word) {
        TrieNode* node = root;
        for (char c : word) {
            int i = c - 'a';
            if (!node->children[i]) {
                node->children[i] = new TrieNode();
            }
            node = node->children[i];
        }
        node->word = word;
    }

    // DFS to find the longest buildable word
    void dfs(TrieNode* node) {
        // Base case is handled by loop condition
        for (int i = 0; i < 26; ++i) {
            if (node->children[i] && !node->children[i]->word.empty()) {
                TrieNode* child = node->children[i];
                
                // A candidate is found
                string candidate = child->word;
                if (candidate.length() > result.length()) {
                    result = candidate;
                } else if (candidate.length() == result.length() && candidate < result) {
                    result = candidate; // Lexicographically smaller
                }

                // Continue searching from this valid word node
                dfs(child);
            }
        }
    }

public:
    string longestWord(vector<string>& words) {
        root = new TrieNode();
        for (const string& word : words) {
            insert(word);
        }

        result = "";
        // Start DFS from the root. The children of the root are words of length 1,
        // which are the base cases for buildable words.
        // The logic inside dfs ensures we only proceed down a path if the child node represents a word.
        dfs(root);

        // The Trie should be cleaned up in a real application, but is omitted here for simplicity.
        return result;
    }
};

Longest Word in Dictionary in TypeScript

function longestWord(words: string[]): string {
    // TrieNode can be represented as an object with potential children and a 'word' property.
    interface TrieNode {
        [key: string]: TrieNode | string;
    }

    const root: TrieNode = {};

    // Build the Trie
    for (const word of words) {
        let node: TrieNode = root;
        for (const char of word) {
            if (!node[char]) {
                node[char] = {};
            }
            node = node[char] as TrieNode;
        }
        node.word = word;
    }

    let result: string = "";

    // DFS function to traverse the Trie
    const dfs = (node: TrieNode) => {
        for (const key in node) {
            if (key === 'word') continue;

            const childNode = node[key] as TrieNode;
            // Check if the child node represents a complete word
            if (typeof childNode.word === 'string') {
                const candidate = childNode.word as string;

                // Update result if the candidate is a better answer
                if (candidate.length > result.length) {
                    result = candidate;
                } else if (candidate.length === result.length && candidate < result) {
                    result = candidate;
                }

                // Continue searching from this valid buildable word
                dfs(childNode);
            }
        }
    };

    dfs(root);
    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.