Word Ladder II

List every shortest chain of words from one word to another, changing one letter per step.

Given two words, beginWord and endWord, and a list of words wordList, return all the shortest sequences that turn beginWord into endWord. Each step changes exactly one letter, and every word after the first must be in wordList. All words have the same length and use lowercase letters. The sequences can come in any order, and if there is none, return an empty list.

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

The Idea

This is the old word ladder puzzle: get from one word to another by changing one letter at a time, where every word on the way must be a real word. A word counts as real only if wordList holds it, and we want every ladder with the fewest steps, not just one.

In Example 1, hit becomes hot by changing i to o. From hot, changing h to d gives dot, then dog, then cog. That is four steps. Changing h to l instead gives lot, log and cog, also four steps. Both ladders are in the answer. So two questions come up: how can we be sure no ladder with three steps exists, and how do we collect every four-step ladder without missing one?

Start from hit and ask which list words are one change away. Only hot is. From hot, dot and lot are one change away. From those, dog and log, and from those, cog. Grouping the words by how many steps they are from hit gives layers. Look at the picture below.

The words of Example 1 in layers: hit on layer 0, hot on layer 1, dot and lot on layer 2, dog and log on layer 3, cog on layer 4. Arrows go from each word to the words one letter away on the next layer, and cog has two incoming arrows, from dog and from log.

hit sits alone on layer 0, hot on layer 1, dot and lot on layer 2, dog and log on layer 3, and cog on layer 4. Each word appears on the first layer that reaches it. cog is on layer 4, so the shortest ladder has four steps, and no shorter one can exist.

The words and the "one letter apart" links between them form a graph: the words are its points, and each link joins two words that differ in one letter. Visiting a graph one layer at a time, nearest words first, is called breadth-first search.

Now look at cog. Two arrows lead into it, one from dog above it and one from log below it. Call the words on the previous layer that lead to a word its parents: cog has two parents, dog and log. dog has one parent, dot, and dot has one, hot. If every word remembers all its parents, each shortest ladder can be read backwards: start at cog, pick a parent, then a parent of that parent, until you reach hit.

Look at the dashed lines too, labelled "same-layer links are not used". dot and lot are one letter apart, but both are on layer 2, so stepping from one to the other never makes a ladder shorter. Only arrows from one layer to the next count.

Solution Approach

Turning that idea into code means seeing first why trying every ladder is slow, then settling four things: how to find the words one letter away, how to build the layers and when to stop, when to cross a word off, and how to read the ladders back.

Trying every ladder

Why not start at beginWord, follow every possible chain of words, and keep the shortest chains that end at endWord? The number of chains grows with every step, because each word can lead to several others. Most of those chains are longer than needed, so almost all that work is thrown away. Building the layers first tells us the shortest length before any ladder is written out.

Finding the words one letter away

How do we find the words one change away from hot? One way is to compare hot with every word in the list, letter by letter. A quicker way for short words is to try every change: put each of the 26 letters at each position, and check whether the new word is in a HashSet of the list. A three-letter word needs 3 × 26 = 78 checks, however long the list is.

Building the layers and when to stop

Which words go on the next layer? Every word one change away from a word on the current layer, as long as it has not appeared on an earlier layer. While a layer is built, each new word also records the word it came from as a parent.

When should the search stop? As soon as a layer contains endWord. That layer is finished first, so endWord collects all its parents, but no further layer is built: deeper layers can only add longer ladders.

When to cross a word off

How do we keep words from earlier layers out? Keep a set of words not yet used, and remove the words of a layer from it. The timing matters. If a word is removed the moment it is first found, a second word on the same layer that also reaches it finds it gone. In Example 1, cog would be removed when the first of its two parents finds it, and the other parent would never be recorded.

So the words of a new layer are removed only after the whole layer is built. Words of earlier layers are still excluded, which keeps every recorded ladder shortest.

Reading the ladders back

How do we turn the parents into ladders? Start a path holding only endWord. For each parent, put it at the front of the path and continue from that parent the same way. When the front word is beginWord, the path is a complete ladder and a copy goes into the answer. Then the parent is taken off the front again, so the next parent can be tried. Trying a choice, following it to the end, and undoing it to try the next is called backtracking.

Java Solution

The method findLadders works in these steps:

  1. First, copy wordList into a HashSet named unused, the words not on any layer yet, and create an empty list result. If endWord is not in unused, return the empty result. Otherwise remove beginWord from unused, in case the list contains it.
  2. Create a map named parents, from a word to the list of its parents, a set named level holding the current layer, which starts as just beginWord, and a flag named found. A while loop builds one layer per round, as long as level is not empty and endWord has not been found.
  3. Inside, create an empty set nextLevel. For each word in level, two loops, one inside the other, try every position i and every letter ch from a to z, building the changed word next.
  4. If next is in unused, add it to nextLevel and add the current word to its list in parents. If next is endWord, set found to true.
  5. When the layer is finished, remove all of nextLevel from unused with unused.removeAll(nextLevel), and make nextLevel the new level.
  6. After the loop, if found is true, start a LinkedList named path holding endWord and call backtrack. It puts each parent at the front with addFirst, calls itself from that parent, and takes the parent off again with removeFirst. When it reaches beginWord, it adds a copy of path to result.
  7. Finally, return result.

The main method runs both examples, a list with three shortest ladders that also contains beginWord, a one-step ladder, and a list where endWord is present but cannot be reached.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class WordLadderII {

    public static List<List<String>> findLadders(String beginWord, String endWord,
                                                 List<String> wordList) {
        Set<String> unused = new HashSet<>(wordList);
        List<List<String>> result = new ArrayList<>();
        if (!unused.contains(endWord)) {
            return result;                    // endWord can never be reached
        }
        unused.remove(beginWord);

        // 1. Visit the words layer by layer, remembering every parent of each word.
        Map<String, List<String>> parents = new HashMap<>();
        Set<String> level = new HashSet<>(List.of(beginWord));
        boolean found = false;
        while (!level.isEmpty() && !found) {
            Set<String> nextLevel = new HashSet<>();
            for (String word : level) {
                char[] chars = word.toCharArray();
                for (int i = 0; i < chars.length; i++) {
                    char original = chars[i];
                    for (char ch = 'a'; ch <= 'z'; ch++) {
                        chars[i] = ch;
                        String next = new String(chars);
                        if (!unused.contains(next)) {
                            continue;         // not in the list, or on an earlier layer
                        }
                        nextLevel.add(next);
                        parents.computeIfAbsent(next, k -> new ArrayList<>()).add(word);
                        if (next.equals(endWord)) {
                            found = true;
                        }
                    }
                    chars[i] = original;
                }
            }
            unused.removeAll(nextLevel);      // only now, so a word keeps all its parents
            level = nextLevel;
        }

        // 2. Walk the parent links back from endWord to beginWord.
        if (found) {
            LinkedList<String> path = new LinkedList<>(List.of(endWord));
            backtrack(endWord, beginWord, parents, path, result);
        }
        return result;
    }

    private static void backtrack(String word, String beginWord,
                                  Map<String, List<String>> parents,
                                  LinkedList<String> path, List<List<String>> result) {
        if (word.equals(beginWord)) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (String p : parents.getOrDefault(word, List.of())) {
            path.addFirst(p);                 // put the parent in front
            backtrack(p, beginWord, parents, path, result);
            path.removeFirst();               // take it off again for the next parent
        }
    }

    public static void main(String[] args) {
        System.out.println(findLadders("hit", "cog",
                List.of("hot", "dot", "dog", "lot", "log", "cog")));
        System.out.println(findLadders("hit", "cog",
                List.of("hot", "dot", "dog", "lot", "log")));
        System.out.println(findLadders("red", "tax",
                List.of("ted", "tex", "red", "tax", "tad", "den", "rex", "pee")));
        System.out.println(findLadders("hot", "dot", List.of("dot")));
        System.out.println(findLadders("hit", "cog", List.of("hot", "cog")));
    }
}

Running it prints:

Output
[[hit, hot, lot, log, cog], [hit, hot, dot, dog, cog]]
[]
[[red, ted, tad, tax], [red, ted, tex, tax], [red, rex, tex, tax]]
[[hot, dot]]
[]

Look at the first line: both ladders of Example 1, but with the lot ladder first. The layers are hash sets, which hand out their words in an order of their own, and the problem accepts the ladders in any order.

The third line turns red into tax in three steps, three different ways. tex appears in two of them because it has two parents, ted and rex. red is also in that list, but it was removed from unused at the start, so no ladder returns to it.

The last line is empty even though cog is in the list. From hit the only word one change away is hot, and nothing in the list is one change away from hot, so the next layer is empty and the loop ends with found still false.

The timing of removeAll is what gives the first and third lines all their ladders. Moving the removal up, to remove each word from unused as soon as it is added to nextLevel, changes the first line to [[hit, hot, lot, log, cog]] and the third to [[red, ted, tad, tax]]: cog and tex each keep only the first parent that found them.

Complexity

The work is building the layers, where each word is expanded once, plus writing out the ladders. N stands for the number of words in wordList, and L for the length of one word.

  • Time: O(N × 26 × L2) for the layers, because each word is expanded once, trying 26 letters at L positions, and each try builds and hashes an L-letter string. Writing out the ladders adds their total length, which can grow very fast when many words have several parents.
  • Space: O(N × 26 × L) besides the answer, because the sets hold each word of L letters at most once, and a word's parent list can hold one entry for each of its 26 × L possible changes.

When only the number of steps of the shortest ladder is needed, words can be crossed off as soon as they are found: see Word Ladder.