Word Ladder

Graphs, problem 8 of 8

Word Ladder

Hard

LC #127

bfsshortest pathimplicit graph

Not attempted yet

Transform begin_word into end_word by changing one letter at a time. Every intermediate word, and end_word itself, must be in word_list (begin_word need not be).

Return the number of words in the shortest such sequence, counting both ends, or 0 if no sequence exists.

Example 1

Input: begin_word = "cold", end_word = "warm",
       word_list = ["cord","card","ward","warm",
                    "corm","worm","word"]
Output: 5

cold → cord → card → ward → warm

Example 2

Input: begin_word = "cold", end_word = "warm",
       word_list = ["cord","card","ward"]
Output: 0

"warm" is not in the list.

Example 3

Input: begin_word = "a", end_word = "c",
       word_list = ["a","b","c"]
Output: 2

Constraints

  • 1 <= len(begin_word) <= 10; all words have the same length and use lowercase letters
  • 1 <= len(word_list) <= 5000, words are distinct
  • begin_word != end_word

Python

Loading draft…

Test results

8 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 5 hidden

Run examples, then submit all tests.