State-Space Search (BFS / DFS / A*)

Word Ladder

Hard
Solve it on LeetCode ↗

The problem

Transform beginWord into endWord one letter at a time, every intermediate word appearing in the word list. Return the length of the shortest sequence (counting both endpoints), or 0.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Load the word list into a set; bail early if endWord is absent.
  2. 2BFS from beginWord at level 1.
  3. 3Neighbor generation: for each position, substitute each of the 26 letters and keep candidates present in the set.
  4. 4REMOVE words from the set as you enqueue them (they can never be reached shorter again).
  5. 5Return the level where endWord appears, else 0.

Key insight

Deleting visited words from the dictionary doubles as the visited-set AND shrinks future neighbor scans — the neighbor-generation trick turns O(N²·L) edge-finding into O(N·L·26).

The solution

Watch out for

  • The count includes BOTH endpoints — "hit → cog" through 5 words returns 5, not 4.
  • beginWord need not be in the list, but endWord MUST be.