#127

Word Ladder

Hard BFS on implicit graph

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Transform beginWord into endWord by changing one letter at a time, where every intermediate word must be in wordList. Return the number of words in the shortest such sequence, or 0.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the shortest chain of one-letter changes from begin to end.

Why this works: words are nodes and one-letter changes are edges. The shortest path in an unweighted graph is BFS.

Example: hit → hot → dot → dog → cog

5 words

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Comparing every pair of words to build edges — O(N² · L).

Solve on LeetCode ↗
Complexity
  • Time: O(N · L · 26), N = words, L = word length.
  • Space: O(N · L).
Topic: Graphs
🎬 Episodes 74–85: video coming soon