Word Ladder

Find the fewest words it takes to turn one word into another, changing one letter at a time.

Given two words, beginWord and endWord, and a list of words, wordList, build a sequence of words that starts with beginWord and ends with endWord. Each word in the sequence differs from the one before it in exactly one letter, and every word after the first must be in wordList. Return the number of words in the shortest such sequence, or 0 if no sequence exists. All words have the same length and use only the lowercase letters a to z.

Example 1
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: hit → hot → dot → dog → cog has 5 words.
Example 2
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: "cog" is not in the list, so no sequence can end with it.
Solution

The Idea

This is the word puzzle where you turn one word into another by changing a single letter at a time, and every word along the way must be a real word. Here "real" means "in wordList", and the goal is to use as few words as possible.

Try it with Example 1. From hit, the only listed word one letter away is hot, made by changing i to o. From hot, changing the h gives dot and lot. From dot, changing t to g gives dog, and from dog, changing d to c gives cog. That is hit, hot, dot, dog, cog: five words.

But other routes exist. Hit, hot, lot, log, cog also has five words, and hit, hot, dot, lot, log, cog has six. With a longer list, the routes multiply quickly. How can we be sure we found the shortest one without trying them all?

Draw the words of Example 1 as boxes and join two boxes with a line when the words differ in exactly one letter. Look at the picture below. The line between hit and hot is labelled "i to o", the letter change that connects them. Boxes joined by lines like this form a graph: each box is a vertex, each line an edge, and two words joined by an edge are neighbours.

The words of Example 1 as a graph, with a line between words that differ in one letter. Columns labelled 1 word to 5 words: hit, then hot, then dot and lot, then dog and log, then cog. The sequence hit, hot, dot, dog, cog is highlighted.

The boxes are placed in columns by how many words the shortest sequence from hit needs to reach them. Hit is in the column labelled "1 word", and hot is in "2 words". Dot and lot are neighbours of hot, so they sit in "3 words". Dog and log come next, in "4 words", and cog is in "5 words".

Building those columns one at a time is the key. First take every word one change from hit, then every new word one change from those, and so on. Every sequence of four words or fewer is used up before the column labelled "5 words" begins. So the first time cog turns up, no shorter sequence can exist.

Searching a graph this way, all the vertices one edge away before any vertex two edges away, is called breadth-first search, or BFS for short. The name comes from the way the search spreads across a whole column before going deeper. In Example 2, cog is missing, so no column ever holds it, and the answer is 0.

Solution Approach

Turning the columns into code means settling four things: how to visit the words column by column, how to find a word's neighbours, how to avoid visiting a word twice, and how to count the words in the sequence.

Visiting the words column by column

How do we keep the columns in order? A queue does it: words join at the back and leave from the front, so they leave in the order they joined. Start the queue with hit. Taking hit out adds hot at the back, and taking hot out adds dot and lot. Every word of one column joins the queue before any word of the next.

To know where one column ends, the code notes how many words the queue holds when the column starts, and takes out exactly that many. Words added in the meantime wait at the back for the next column.

Finding a word's neighbours

Which words are neighbours of hot? One way is to build the whole graph first, as an adjacency list: for each word, the list of its neighbours, such as hot: hit, dot, lot. Building it compares every word with every other word, which is slow when the list holds thousands of words.

The neighbours can be made on the spot instead. For each letter of hot, try all 26 letters in its place: aot, bot, cot, and so on, then hat, hbt, and so on. Most of these made-up words are not in the list. Each attempt is looked up in a HashSet of the listed words, a lookup that takes about the same time however many words the set holds. A word of three letters needs only 3 × 26 = 78 lookups.

Not visiting a word twice

What stops the search from going back from hot to hit, or reaching dot twice? Once a word joins the queue, it is already in the earliest column it can be in, so any later path to it is longer. The code keeps the words not yet reached in a set and removes each word as it joins the queue. A made-up word that is not in the set is then either missing from the list or already reached, and the search skips it either way.

Counting words, not changes

The answer counts words, not letter changes: hit to cog takes four changes but five words. So the count starts at 1, for beginWord on its own, and grows by one after each column. When cog comes out of the queue, the count is 5, the label of its column in the picture.

Java Solution

The method ladderLength works in these steps:

  1. First, copy wordList into a HashSet named unused, which holds the words not reached yet. If endWord is not in it, return 0 at once, as Example 2 does.
  2. Create the queue, an ArrayDeque named queue, and add beginWord to it. Remove beginWord from unused in case the list holds it, and set length to 1.
  3. A while loop runs as long as queue holds words, one pass per column. Inside it, a for loop reads the queue's size when the column starts and takes out exactly that many words with poll().
  4. If the word taken out equals endWord, return length. Otherwise copy the word into a char array named chars. For each position i, keep the letter in original, then try every letter from 'a' to 'z' in its place and build the string next.
  5. unused.remove(next) returns true only if next was still in the set, so one call both checks the word and marks it reached. On true, add next to the queue. After the 26 letters, put original back before moving to the next position.
  6. After each column, add 1 to length. If the queue runs empty without reaching endWord, return 0.

The main method runs both examples, a sequence of a single change, and a list that holds endWord but no route to it.

Java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class WordLadder {

    public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
        Set<String> unused = new HashSet<>(wordList);
        if (!unused.contains(endWord)) {
            return 0;                                  // endWord can never be reached
        }
        Deque<String> queue = new ArrayDeque<>();
        queue.add(beginWord);
        unused.remove(beginWord);
        int length = 1;                                // counts words, so beginWord alone is 1
        while (!queue.isEmpty()) {
            for (int size = queue.size(); size > 0; size--) {   // one column at a time
                String word = queue.poll();
                if (word.equals(endWord)) {
                    return length;
                }
                char[] chars = word.toCharArray();
                for (int i = 0; i < chars.length; i++) {
                    char original = chars[i];
                    for (char ch = 'a'; ch <= 'z'; ch++) {      // every one-letter change
                        chars[i] = ch;
                        String next = new String(chars);
                        if (unused.remove(next)) {             // in the list and not seen yet
                            queue.add(next);
                        }
                    }
                    chars[i] = original;
                }
            }
            length++;
        }
        return 0;                                      // the queue ran dry before endWord
    }

    public static void main(String[] args) {
        System.out.println(ladderLength("hit", "cog",
                List.of("hot", "dot", "dog", "lot", "log", "cog")));
        System.out.println(ladderLength("hit", "cog",
                List.of("hot", "dot", "dog", "lot", "log")));
        System.out.println(ladderLength("hit", "hot", List.of("hot")));
        System.out.println(ladderLength("hit", "cog", List.of("hot", "cog")));
    }
}

Running it prints:

Output
5
0
2
0

The 5 on the first line matches the column labelled "5 words" in the picture. The 0 below it comes from the check in step 1: cog is missing from the list, so the search never starts.

The third line, 2, is hit to hot. That is one change but two words, because length starts at 1 for hit itself. The last line is 0 for a different reason. Cog is in the list, but the only word one change from hit is hot, and hot differs from cog in two letters. The queue holds hot, finds nothing new from it, and runs empty.

Complexity

Each word leaves the queue at most once, and for each one the code tries 26 letters at each position. Here N is the number of words in wordList and L is the length of each word.

  • Time: O(26 × N × L2), because each of the N words makes 26 attempts at each of its L positions, and building and hashing each attempt reads all L letters.
  • Space: O(N × L), because unused starts with all N words of L letters each, and the queue holds each word at most once.

Listing every shortest sequence, not just counting its words, is Word Ladder II.