iq.lab
Python starts when a code cell comes near or you run one
hardBreadth-first searchHash maps and sets target 40 min

Word ladder

You get a start word begin_word, a target word end_word and a list of allowed words word_list. All the words have the same length and use lowercase letters. A ladder goes from begin_word to end_word one word at a time, and each word differs from the word before it in exactly one position. begin_word may be missing from the list, but every later word on the ladder must come from it. The list may also hold a word twice, or hold begin_word.

Count the words on the shortest ladder, with begin_word and end_word both included, and return that count. If no ladder exists, for example because end_word is not in the list, return 0.

Example 1
Inputbegin_word = "cat", end_word = "dog", word_list = ["cot", "cog", "dog", "cut", "dot"]Output4

One shortest ladder is cat, cot, cog, dog. cat and dog differ in all three positions, and each step changes one letter, so no ladder can be shorter than 4 words.

Example 2
Inputbegin_word = "cold", end_word = "warm", word_list = ["cord", "card", "ward", "warm", "worm", "word"]Output5

cold, cord, card, ward, warm. cold and warm differ in all four positions, so no ladder can be shorter than 5 words.

Example 3
Inputbegin_word = "lead", end_word = "gold", word_list = ["load", "goad", "goal"]Output0

gold is not in the list, so no ladder can end there. lead, load, goad, gold would work if it were.

Constraints
  • 1 ≤ length of each word ≤ 10

  • 1 ≤ len(word_list) ≤ 104

  • All words have the same length and only lowercase letters.

  • begin_word != end_word

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.