Algo-Sim › Graph Traversal

Word Ladder

Hard · Graph Traversal · step through it in Java, Python and C++ on your own input

Change one letter at a time, using only words from the list, to turn beginWord into endWord. Return the number of words in the shortest ladder, or 0.

Problem

Turn beginWord into endWord one letter at a time, where every intermediate word must be in wordList. Return the number of words in the shortest such sequence, counting both ends, or 0 if it cannot be done.

Constraints

Edge cases to test

Follow-up questions

How do you find neighbours fast?
Map each pattern like h*t to its words, so a word’s neighbours come from L patterns: O(N·L²) overall.
How do you make it faster?
Bidirectional BFS: search from both ends, expand the smaller frontier each round and stop when a new word is in the other frontier. With branching b and distance d, that is about 2·b^(d/2) words instead of b^d.
How do you list every shortest sequence?
BFS to record each word’s parents by level, then backtrack from endWord (LC 126).

Solution

Java

public int ladderLength(String beginWord, String endWord, List<String> wordList) {
    Set<String> words = new HashSet<>(wordList);
    if (!words.contains(endWord)) return 0;
    Queue<String> queue = new ArrayDeque<>();
    queue.offer(beginWord);
    words.remove(beginWord);
    int length = 1;
    while (!queue.isEmpty()) {
        for (int size = queue.size(); size > 0; size--) {
            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 c = 'a'; c <= 'z'; c++) {
                    chars[i] = c;
                    String next = new String(chars);
                    if (words.remove(next)) queue.offer(next);
                }
                chars[i] = original;
            }
        }
        length++;
    }
    return 0;
}

Python

from collections import deque
from string import ascii_lowercase


def ladder_length(begin_word, end_word, word_list):
    words = set(word_list)
    if end_word not in words:
        return 0
    queue = deque([begin_word])
    words.discard(begin_word)
    length = 1
    while queue:
        for _ in range(len(queue)):
            word = queue.popleft()
            if word == end_word:
                return length
            for i in range(len(word)):
                for c in ascii_lowercase:
                    nxt = word[:i] + c + word[i + 1:]
                    if nxt in words:
                        words.remove(nxt)
                        queue.append(nxt)
        length += 1
    return 0

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int ladderLength(string &beginWord, string &endWord, vector<string> &wordList) {
        unordered_set<string> words = unordered_set<string>(wordList.begin(), wordList.end());
        if (!words.count(endWord))
            return 0;
        deque<string> queue = {};
        queue.push_back(beginWord);
        words.erase(beginWord);
        int length = 1;
        while (!queue.empty()) {
            for (int size = int(queue.size()); size > 0; size--) {
                string word = queue.front();
                queue.pop_front();
                if ((word == endWord))
                    return length;
                string chars = word;
                for (int i = 0; i < int(chars.size()); i++) {
                    char original = chars[i];
                    for (char c = 'a'; c <= 'z'; c++) {
                        chars[i] = c;
                        string next = string(chars.begin(), chars.end());
                        if (words.erase(next))
                            queue.push_back(next);
                    }
                    chars[i] = original;
                }
            }
            length++;
        }
        return 0;
    }
};

More Graph Traversal problems