Shortest Word Chain

HardGraphs≈ 55 min

A word chain goes from the word begin to the word end one step at a time: each step changes exactly one letter of the word, and every word after begin must be one of the words in the list words. Return the number of words in the shortest chain, begin and end included, or 0 if there is no chain.

All words are the same length and written in lowercase letters. begin does not have to be in the list; end does, or there can be no chain. begin and end are different words.

Examples

text
begin = "cold", end = "warm", words = ["cord", "card", "ward", "warm", "word", "worm", "corm"]   →  5
begin = "hit", end = "cog", words = ["hot", "dot", "dog", "lot", "log"]                          →  0
begin = "hit", end = "cog", words = ["hot", "dot", "dog", "lot", "log", "cog"]                   →  5
begin = "ab", end = "cd", words = ["ad", "cd"]                                                   →  3

In the first example cold → cord → word → worm → warm, five words. In the second, "cog" is not in the list, so no chain can end there.

Constraints

  • Words between 1 and 10 letters long, and up to 1,000 words in the list.
  • Aim for time that grows like n, the number of words, for words of a fixed length: comparing every word with every other one grows like n².
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.