HardPro challengePythonJavaScriptTypeScript
Graph — Word Ladder
Data StructuresGraphsBFSStrings
solve(beginWord, endWord, wordList) — transform beginWord into endWord by
changing one letter at a time; every intermediate word must be in wordList
(beginWord itself does not have to be). Return the number of words in the
shortest transformation sequence, counting both ends, or 0 if there is none.
Words are nodes, and two words are connected when they differ by exactly one
letter, so this is a BFS for the shortest path in an implicit graph.
Examples
solve("hit", "cog", ["hot","dot","dog","lot","log","cog"]) → 5 // hit→hot→dot→dog→cog
solve("hit", "cog", ["hot","dot","dog","lot","log"]) → 0 // "cog" is missing
solve("a", "c", ["a","b","c"]) → 2
solve("red", "tax", ["ted","tex","red","tax","tad","den","rex","pee"]) → 4All words have the same length and are lowercase. Generating neighbours by trying
each of the 26 letters at every position is much cheaper than comparing every pair.
Sample tests
Test #1Classic example
Input: ["hit","cog",["hot","dot","dog","lot","log","cog"]]
Output: 5
Test #2End word is not in the list
Input: ["hit","cog",["hot","dot","dog","lot","log"]]
Output: 0
Test #3One step
Input: ["a","c",["a","b","c"]]
Output: 2