Word Ladder
Given beginWord, endWord and a word list, return the length of the shortest transformation sequence from beginWord to endWord — every step changes exactly one letter, and every intermediate word (and endWord) must be in the list. Return 0 when no sequence exists. The length counts words, so hit → hot → dot → dog → cog is 5.
ladderLength("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"]) -> 5
ladderLength("hit", "cog", ["hot", "dot", "dog", "lot", "log"]) -> 0Hints
Hint 1
It is a shortest path in an implicit graph, so BFS by levels: from each frontier word, try every position and every letter, keep the candidates that are still in the word set, and remove them from the set as you enqueue them.
Hint 2
Bidirectional BFS expands the smaller frontier from either end and stops when a candidate is in the other side; it roughly square-roots the explored space.