CODING CHALLENGE · N°44

Word Ladder

Hard GraphsBFSStrings

Transform one word into another by changing a single letter at a time, where every step must be a real word. The shortest such chain is a shortest path in a hidden graph — so it is a job for breadth-first search. Return the length of the shortest ladder. Solve it in Python or TypeScript, with hidden tests.

The problem

Given a begin word, an end word, and a list of allowed words, return the number of words in the shortest transformation sequence from begin to end, changing exactly one letter at a time, where every intermediate word (and end) must be in words. Count both endpoints. Return 0 if no such sequence exists.

EXAMPLE 1
Input begin = 'hit', end = 'cog', words = ['hot','dot','dog','lot','log','cog']
Output 5
hit → hot → dot → dog → cog is 5 words
EXAMPLE 2
Input begin = 'hit', end = 'cog', words = ['hot','dot','dog','lot','log']
Output 0
end word "cog" is not in the list
CONSTRAINTS
  • All words have the same length and are lowercase; begin need not be in words, but end must be.
  • Each step changes exactly one letter and must land on a word in the list.
  • The answer counts words (nodes), not steps — the shortest chain of length k has k words. BFS gives the shortest.
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement ladder_length(begin, end, words): BFS from begin, where a word’s neighbours are the words in the set reachable by changing one letter. Track the depth (word count); the first time you reach end, return it. Return 0 if BFS exhausts.

HINTS — 4 IDEAS
  1. Put the word list in a set for O(1) membership. If end is not in it, the answer is 0 immediately.
  2. BFS level by level from begin, carrying the number of words used so far (start at 1).
  3. Neighbours of a word: for each position, try all 26 letters; keep those that are in the set and not yet visited.
  4. The first time you dequeue end, its depth is the shortest ladder length. BFS guarantees shortest-first.
CPython · WebAssembly

Explore the topic

See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.