Word Ladder
Find the length of the shortest transformation sequence from beginWord to endWord, changing one letter at a time through words in wordList.
Intuition
It is tempting to compare every word against every other word to decide which pairs are one letter apart, but that is O(n^2 L) before the BFS even starts. Instead, never build the graph at all: for the current word, try swapping in each of the 26 letters at each position, and check whether the result is in the word set. That generates exactly the neighbors that matter, on demand, in O(L 26) per word. The graph is implicit - it exists only as a rule for generating edges, computed lazily as BFS needs them.
Approach
Guard the target
If endWord is not in wordList, no sequence of legal one-letter swaps can ever land on it, so return 0 immediately.
Generate neighbors on demand
From the current word, for each position and each of the 26 letters, build the candidate word. If it is in the word set and unvisited, it is a genuine neighbor - no precomputed adjacency list needed.
BFS layer = transformation count
Track distance from beginWord (starting at 1). The first time endWord is generated, its distance is the answer, since BFS explores shortest sequences first.
Solution & live demo
Edge cases
Return 0 right away, no BFS needed.
Not a valid LeetCode input, but would resolve trivially.
They are simply never generated as neighbors and never visited.
BFS queue empties without reaching endWord; return 0.