AAlgoLoopSpaced repetition for LeetCode
HARDBFS / DFSLeetCode ↗

Word Ladder

The key idea

Treat each word as a node and connect two words with an edge when they differ by exactly one letter. The shortest transformation sequence is then the shortest path from beginWord to endWord, which an unweighted BFS finds level by level.

Problem

A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that every adjacent pair of words differs by a single letter, every si for 1 <= i <= k is in wordList (note that beginWord does not need to be in wordList), and sk == endWord. Given two words beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.

Constraints

Examples

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: 5
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: 0

Complexity

Time: O(N * L^2) Space: O(N * L)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems