Longest Word With All Prefixes

Pattern: Word counting

medium

Insert every word; then walk from the root entering only children that end a word, so every prefix along the way is in the list. The deepest such node gives the answer; visiting letters in order makes the first longest word the smallest.

The problem

Return the longest word in words such that every prefix of it is also in words. Break ties by the smallest word in alphabetical order; return an empty string if there is none.

Think first

  • Which nodes may the walk enter?
  • How are ties broken cheaply?
  • When is the answer empty?

Hints

    Brute force, and why it fails

    For each word check every prefix in a hash set: O(n × L²), still fine; sort for ties.

    The key insight

    A walk restricted to end nodes visits exactly the words whose prefixes are all present.

    Dry run

    k, ki, kir, kira, kiran: every step ends a word.

    Step 1 of 2

    The plan

    insert all words
    dfs(node, word): if longer than best: best = word
      for c in a..z: if child c ends a word: dfs(child, word + c)
    

    Complexity

    Time
    O(total letters)
    Space
    O(total letters)

    Each node at most once.

    Edge cases

    • No one-letter word: empty.
    • Ties.
    • Duplicate words.
    I've built my logic, show the code

    Java

    class Solution {
        private static class Node {
            Node[] next = new Node[26];
            boolean end;
        }
    
        private String best = "";
    
        public String longestWord(String[] words) {
            Node root = new Node();
            for (String w : words) {
                Node n = root;
                for (char c : w.toCharArray()) {
                    if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node();
                    n = n.next[c - 'a'];
                }
                n.end = true;
            }
            best = "";
            walk(root, new StringBuilder());
            return best;
        }
    
        private void walk(Node n, StringBuilder word) {   // only go down through nodes where a word ends
            if (word.length() > best.length()) best = word.toString();   // letters in order: the first longest is the smallest
            for (int c = 0; c < 26; c++)
                if (n.next[c] != null && n.next[c].end) {
                    word.append((char) ('a' + c));
                    walk(n.next[c], word);
                    word.deleteCharAt(word.length() - 1);
                }
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> next;
        vector<bool> isEnd;
        string best;
    
        string longestWord(vector<string>& words) {
            next.assign(1, vector<int>(26, 0));
            isEnd.assign(1, false);
            for (const string& w : words) {
                int n = 0;
                for (char c : w) {
                    if (next[n][c - 'a'] == 0) {
                        next[n][c - 'a'] = static_cast<int>(next.size());
                        next.push_back(vector<int>(26, 0));
                        isEnd.push_back(false);
                    }
                    n = next[n][c - 'a'];
                }
                isEnd[n] = true;
            }
            best = "";
            string word;
            walk(0, word);
            return best;
        }
    
        void walk(int n, string& word) {            // only go down through nodes where a word ends
            if (word.size() > best.size()) best = word;   // letters in order: the first longest is the smallest
            for (int c = 0; c < 26; c++)
                if (next[n][c] != 0 && isEnd[next[n][c]]) {
                    word.push_back(static_cast<char>('a' + c));
                    walk(next[n][c], word);
                    word.pop_back();
                }
        }
    };

    Python

    class Solution:
        def longestWord(self, words: list[str]) -> str:
            root = {}
            for w in words:
                node = root
                for c in w:
                    node = node.setdefault(c, {})
                node["$"] = True
            best = ""
    
            def walk(node, word):                   # only go down through nodes where a word ends
                nonlocal best
                if len(word) > len(best):           # letters in order: the first longest is the smallest
                    best = word
                for c in sorted(k for k in node if k != "$"):
                    if "$" in node[c]:
                        walk(node[c], word + c)
    
            walk(root, "")
            return best

    Common mistakes

    • Allowing a missing prefix.
    • Breaking ties by the last found.

    Similar problems