Longest Word in Dictionary

Find the longest word in a list that can be built one letter at a time from other words in the same list.

Given a list of lowercase words, return the longest word that can be built one letter at a time, where every prefix, a start of the word, is also a word in the list. For "apple", that means "a", "ap", "app" and "appl" must all be in the list. If two such words have the same length, return the one that comes first in alphabetical order. If no word qualifies, return the empty string "".

Example 1
Input: words = ["w","wo","wor","worl","world"]
Output: "world"
Example 2
Input: words = ["a","banana","app","appl","ap","apply","apple"]
Output: "apple"
Explanation: "apple" and "apply" can both be built, and "apple" comes first in alphabetical order. But "banana" cannot be built, because "b" is not in the list.
Solution

The Idea

Picture a word game where you lay down one letter tile at a time, and after every tile the letters on the table must spell a word from the list. In Example 2, "apple" grows as a, ap, app, appl, apple, and each of those is in the list. The word "apply" grows the same way up to appl and then adds a y. The word "banana" fails on its first tile, because b alone is not in the list.

Checking a word means checking every start of it, and many words start the same way. The words "apple" and "apply" share their first four letters, so checking them one after the other repeats a, ap, app and appl. How can we check those shared starts only once?

Store the words so that shared starts are stored once. Begin with an empty box, the root. Each letter of a word is a link to a new box, and two words that begin with the same letters follow the same links for as long as their letters agree. Look at the picture below, built from Example 2.

The trie for Example 2. From the root, the links a, p, p, l, e lead to the box apple, and every box on that path ends a word. The link y from appl leads to apply, the same length as apple. The link b leads to a box that is only a prefix, so banana is never reached.

From the root, the link a leads to the box a, then the link p to the box ap, and so on to appl. There the path splits: the link e leads to apple and the link y to apply. Each box is labelled with the letters spelled on the way to it. The box where a word's last letter lands is marked as the end of a word. In the picture, those boxes have a solid border, as the legend "a word ends here" shows. A tree of letter links like this, where words with the same start share a path, is called a trie.

Now look at the dashed boxes along the bottom, labelled "only a prefix". The link b leads to the box b, but no word in the list is just "b", so that box is not a word end. The prefixes ba, ban, bana and banan are not in the list either. Only the last box, banana, ends a word.

So a word can be built one letter at a time exactly when every box on its path from the root ends a word. Follow the orange line marked "the path to apple": a, ap, app, appl and apple all end words. The question for each word turns into a walk: start at the root, step only into boxes that end a word, and keep the longest word you reach. The walk stops at the box b, "not a word: stop", so "banana" is never reached, even though it is the longest word in the list.

One question is left: apply has the same length as apple and is "reached later", as the picture notes. If the walk tries the links of each box in alphabetical order, it goes down e before y, so it meets apple first. Keeping the first word of each length then gives the alphabetically smallest one.

Solution Approach

Turning that walk into code means settling three things: how to store the trie, how to walk only through boxes that end a word, and how to settle ties between words of the same length.

Storing the trie

Why build a trie at all, instead of putting the words in a HashSet and looking up each start of each word? That works too: for "apple" it looks up "a", "ap", "app" and "appl". But each lookup builds a new string and reads it again, so a word of length L costs about L×L/2 letters of work, and the starts that "apple" and "apply" share are checked twice.

In the trie, each box is a small Node object with an array next of 26 slots, one per letter: next[0] is the link a, next[1] the link b, and so on to z. An empty slot is null. A second field, word, holds the word that ends at this box, or null when the box is only a prefix. Keeping the whole word there means the walk can read its length and return it without rebuilding it letter by letter from the path.

Walking only through word ends

In what order should the walk visit the boxes? From the root it goes a, ap, app, appl, apple, as deep as it can along one path. Then it backs up to appl to try the link y, and later all the way back to the root to try the link b. Going deep along one path before backing up to try the next link is called a depth-first search, or DFS for short.

A method dfs(node) does this. For each child box of node, it goes on only if the box exists and its word is not null, and then calls itself on that box to go one letter deeper. Every box it enters is a word end, and so is every box above it, so every word the walk meets can be built.

Settling ties

Which word wins when two have the same length? The loop in dfs reads next from slot 0 to slot 25, which is alphabetical order. Two words of the same length first differ at some letter, and the walk finishes the whole branch under the smaller letter before it starts the bigger one. So the best word is replaced only by a strictly longer word, and a later word of the same length is left out.

Java Solution

The method longestWord works in these steps:

  1. First, create an empty root node. For each word w, a marker cur starts at root and moves down one letter at a time. The slot index is i = ch - 'a', and when cur.next[i] is empty, a new node is created there. After the last letter, cur.word = w marks the end of the word.
  2. Next, call the helper dfs(root), which walks the trie. Its loop takes the children of a node in order from next[0] to next[25] and enters a child only when it is not null and its word is not null.
  3. For each child it enters, dfs compares the child's word with best, the longest word found so far, which starts as "". A strictly longer word replaces best. Then dfs calls itself on the child, to go one letter deeper.
  4. When the walk has come back to the root, longestWord returns best.

The main method runs both examples, the list ["b", "ab"], a list with no one-letter word, and a tie between "kit" and "mit". The helper solve makes a new object for each list, so best starts empty, and puts quotes around the answer so an empty answer is visible.

Java
public class LongestWordInDictionary {

    private static class Node {
        Node[] next = new Node[26];   // one slot per letter, 'a' to 'z'
        String word;                  // the word that ends here, or null
    }

    private String best = "";

    public String longestWord(String[] words) {
        Node root = new Node();
        for (String w : words) {
            Node cur = root;
            for (char ch : w.toCharArray()) {
                int i = ch - 'a';
                if (cur.next[i] == null) {
                    cur.next[i] = new Node();
                }
                cur = cur.next[i];
            }
            cur.word = w;                 // mark the end of w
        }
        dfs(root);
        return best;
    }

    // Walk only into nodes where a word ends, so every prefix on the way is a word.
    private void dfs(Node node) {
        for (Node child : node.next) {    // children in order 'a' to 'z'
            if (child != null && child.word != null) {
                if (child.word.length() > best.length()) {
                    best = child.word;    // strictly longer only
                }
                dfs(child);
            }
        }
    }

    static String solve(String... words) {
        return "\"" + new LongestWordInDictionary().longestWord(words) + "\"";
    }

    public static void main(String[] args) {
        System.out.println(solve("w", "wo", "wor", "worl", "world"));
        System.out.println(solve("a", "banana", "app", "appl", "ap", "apply", "apple"));
        System.out.println(solve("b", "ab"));
        System.out.println(solve("ab", "abc"));
        System.out.println(solve("k", "ki", "kit", "m", "mi", "mit"));
    }
}

Running it prints:

Output
"world"
"apple"
"b"
""
"kit"

On the second line, "apple" wins over "apply", and "banana", the longest word in that list, is not chosen because the box b is only a prefix. The third line is "b": "ab" is longer, but its first step, "a", is not in the list.

In ["ab", "abc"] no word has a single letter, so the walk cannot leave the root, and the fourth line is the empty string. The last line comes from a tie: "kit" and "mit" can both be built, k comes before m, so "kit" is reached first and stays.

The test child.word.length() > best.length() must stay strict. With >= in its place, a later word of the same length replaces the earlier one: running the same main that way prints "apply" on the second line and "mit" on the last.

Complexity

The work is one pass over the letters to build the trie, plus one walk over its boxes. Let T be the total number of letters in all the words together.

  • Time: O(T), because building the trie handles each of the T letters once, and the walk enters each box at most once and scans its 26 slots, a fixed amount per box.
  • Space: O(T) boxes of 26 slots each, because each letter can create its own box, and the chain of dfs calls is only as deep as the longest word.

How a trie inserts and finds words, step by step, is covered in Implement Trie.