Example 1
- Input
- beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
- Output
- 5
The shortest chain is hit to hot to dot to dog to cog, which holds 5 words.
Change one letter at a time to turn the begin word into the end word, using only words from the given list. Return the word count of the shortest such chain, or 0 when no chain exists.
Given beginWord, endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord. Each neighbouring pair in the sequence must differ by exactly one letter, and every intermediate word must appear in wordList.
If no valid sequence exists, return 0. The length counts words, so a direct one-letter change has length 2.
1 <= beginWord.length <= 10endWord.length == beginWord.length1 <= wordList.length <= 5000wordList[i].length == beginWord.lengthbeginWord, endWord, and wordList[i] hold lowercase English letters.beginWord != endWordwordList are unique.The shortest chain is hit to hot to dot to dog to cog, which holds 5 words.
The end word cog is missing from the list, so no valid chain exists.
The target is present, but hit reaches only hot and dot. Dot and cog differ in two letters, so dictionary membership alone does not guarantee a chain.
A direct change from a to c uses two words. The begin word may appear in the dictionary; marking it visited initially prevents revisiting it.
Think of each allowed word as a vertex, with an edge between words differing in exactly one position. Every edge costs one change, so breadth-first search (BFS) explores shorter chains before longer ones. In Example 1, the layers are hit, hot, then dot and lot, then dog and log, then cog: five words. A wildcard such as *ot groups hot, dot and lot without comparing every pair. Once one BFS layer scans that bucket, all its words have already received their earliest possible discovery, so later visits can discard the bucket.
Reveal Compare All Word Pairs: intuition, complexity, and code
h*t group one-apart words together, so neighbours come from a map read instead of a full list scan.0 before any search starts.2 after a single expansion.0.When edges are defined by a small local change, index items by their change patterns so neighbour lookup skips the pairwise scan.