Word Ladder

Hard · Graphs · Hash Table · String · Breadth-First Search

Problem

You are given two words, beginWord and endWord, and a dictionary wordList. A ladder goes from beginWord to endWord one word at a time, where each step changes exactly one letter, and every word after beginWord must be in wordList. beginWord itself does not have to be in the list.

Return the number of words in the shortest ladder, counting both ends. If there is no ladder (including when endWord is not in wordList), return 0.

No graph is given, but there is one: the words are the nodes, and two words are joined when they differ in one position. The question is a shortest path in that unweighted graph.

Examples

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

One shortest ladder is hit → hot → dot → dog → cog, five words.

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

cog is not in the dictionary, so no ladder can end there.

Constraints

Approaches

Follow-up

Can you search from both ends at once, always expanding the smaller frontier? How much does that save when the ladder is long and each word has many neighbors?

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…