Given beginWord, endWord and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, where each step changes exactly one letter and every intermediate word must be in wordList. Return 0 if no sequence exists.
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]5 (hit → hot → dot → dog → cog)beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]0 ("cog" is not in the list)endWord isn't in the list, return 0. Put the list in a HashSetbeginWord at level 1'a'…'z' ("h?t")endWord → return level + 1 🎉DFS may wander down a long ladder first and still has to explore everything to be sure it's the shortest. BFS explores in rings of equal distance, so the first time it touches endWord is the minimum. Mark words seen when you enqueue them (not when you pop) so no word is queued twice. For big inputs, bidirectional BFS from both ends meets in the middle and is much faster.
endWord not in the list → 0 immediately. beginWord doesn't have to be in the list. The answer counts words in the ladder, not moves (hit→hot→dot→dog→cog = 5). Several shortest ladders can exist; BFS returns the length, and all of them are equally short.