Shortest Word Chain
You want to turn the word begin into the word end, changing exactly one letter at a time. Every intermediate word, and end itself, must appear in the list words. begin does not need to be in the list.
Return the number of words in the shortest chain from begin to end, counting both ends. Return 0 if no chain exists. All words have the same length and use lowercase letters.
Example 1
Input: begin = "hit", end = "cog", words = ["hot","dot","dog","lot","log","cog"] Output: 5 Explanation: hit -> hot -> dot -> dog -> cog.
Example 2
Input: begin = "hit", end = "cog", words = ["hot","dot","dog","lot","log"] Output: 0 Explanation: "cog" is not in the list.
Constraints
- 1 <= begin.length <= 10
- 1 <= words.length <= 5000
- begin !== end
Hint 1
Treat each word as a node, with edges between words that differ in one letter. The shortest chain is a BFS.
Hint 2
Instead of comparing every pair of words, generate all one-letter changes of the current word and look them up in a Set.
Good practice for: Backend Developer, Full Stack Developer, Game Developer, AI Engineer (LLM & Generative AI), Data Scientist
Run checks your code on 3 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.