Skip to content

Word Ladder

Find the length of the shortest chain of one-letter changes between two words, with BFS over words.

HardGraph BFS and DFS
Solve on LeetCode

The problem

You get two words of the same length, beginWord and endWord, and a dictionary wordList. A ladder starts at beginWord and changes exactly one letter at each step, and every word after the first must be in wordList. Return the number of words in the shortest ladder that ends at endWord, or 0 if there is none.

Input beginWord = "cold", endWord = "warm", wordList = ["cord", "card", "ward", "warm", "worm", "word", "wore", "core"]

Output 5

One shortest ladder is cold, cord, card, ward, warm, which has 5 words. cold, cord, word, worm, warm is just as short.

Input beginWord = "cold", endWord = "warm", wordList = ["cord", "card", "ward", "worm"]

Output 0

warm is not in the word list, so no ladder can end there.

Key constraint: The list can hold 5,000 words of up to 10 letters. Comparing every pair of words is about 12.5 million comparisons, while trying 26 letters at each position of each word is about 1.3 million lookups.

How to spot the pattern

  • You need the fewest steps from a start to a target, and every step costs the same.
  • The graph is not given: two words are neighbors when they differ in exactly one letter, so you generate neighbors as you go.

The idea

Think of every word as a node, with an edge between words that differ in one letter; the shortest ladder is then a shortest path, which BFS finds level by level. You don't need to build the graph: from a word, try every letter from a to z at every position and keep the results that are in the dictionary. Removing a word from the dictionary when you first reach it marks it as visited, so it is never queued twice.

Brute force: Compare every pair of words to build the graph first, which takes O(n^2 * L) time before the BFS even starts.

Step by step

  1. 1Put wordList in a set, and return 0 if endWord is not in it.
  2. 2Start a queue with beginWord and a ladder length of 1.
  3. 3Process the queue one level at a time, and return the current length when you take out endWord.
  4. 4For each position of the word, try all 26 letters, and queue every resulting word that is still in the set, removing it from the set.
  5. 5Add 1 to the length after each level, and return 0 if the queue runs out.

See the pattern move

The graph bfs and dfs pattern on a small example. Step through it, or press play.

Code

from collections import deque


class Solution:
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        words = set(wordList)
        if endWord not in words:
            return 0
        words.discard(beginWord)  # never come back to the start
        queue = deque([beginWord])
        length = 1  # beginWord itself is the first word of the ladder
        while queue:
            for _ in range(len(queue)):  # every word on this level is `length` words from the start
                word = queue.popleft()
                if word == endWord:
                    return length
                for i in range(len(word)):
                    for letter in "abcdefghijklmnopqrstuvwxyz":
                        nxt = word[:i] + letter + word[i + 1:]
                        if nxt in words:
                            words.remove(nxt)  # removing it marks it as visited
                            queue.append(nxt)
            length += 1
        return 0

Complexity

Time

O(n * L^2)

Space

O(n * L)

n is the number of words and L their length: each word leaves the queue once, and each of its 26 * L variations costs O(L) to build and look up; the set and the queue hold O(n * L) characters.

Watch out for

  • Returning the number of changes instead of the number of words: the one-step ladder from dig to dog has 2 words.
  • Marking words as visited only when you take them out of the queue, so the same word can be queued many times.
  • Forgetting that a missing endWord gives 0, even when beginWord is one letter away from it.

Follow-up questions

How can you make it faster?

Run BFS from both ends at once and always expand the smaller frontier; the two searches meet in the middle and visit far fewer words. Grouping words by patterns like c*ld also finds all neighbors of a word with one lookup per position.

What if you must return every shortest ladder?

Run the same BFS, but for each word remember all the words on the previous level that lead to it. Then walk back from endWord along those links to list the ladders. That is Word Ladder II.

In Hinglish

Har word ek node hai aur ek letter ka farak ek edge. BFS mein har position par a se z tak try karo; jo word set mein mile use queue mein daalo aur set se hata do.

Related problems