Skip to the solution
HardDSA15 min read

How do you solve the word ladder problem?

817 views

The problem

Question presented to candidate: "Given a begin word, an end word and a list of dictionary words, find the number of words in the shortest transformation sequence from begin to end, where each step changes exactly one letter and every intermediate word must be in the list. Return 0 if there is no such sequence. Please code it in Python."

What a strong answer should cover:

  • Modelling: words are nodes, one-letter changes are edges, and the graph is implicit — generated on demand, not stored.
  • BFS because every edge has the same cost, so the first time end is reached is the shortest chain; the answer counts words, not steps.
  • Neighbour generation: 26 letters × L positions, kept only if the candidate is in a set; mark visited when queued (e.g. by removing from the set).
  • Complexity O(N · 26 · L²) time and O(N · L) space, and why comparing all pairs, O(N² · L), is worse for large N.
  • Python specifics: set (not list) for membership, collections.deque, string.ascii_lowercase, and the O(L) cost of word[:i] + ch + word[i+1:] because strings are immutable. Bidirectional BFS as the follow-up optimisation.

Clarifying questions expected:

  • Count words or steps? Must endWord be in the list?
  • Do you want the sequence itself, or all shortest sequences?

Code / implementation expected: Yes — a ladder_length(begin, end, word_list) in Python using BFS with a set, ideally also returning the chain via a parent map.

  • graphs
  • bfs

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read · 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBFS word ladder on six inputs, printing the shortest chain
PythonOne-way BFS vs bidirectional BFS: words expanded on generated dictionaries

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 139 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

Longest increasing path in matrix — why DFS + memo beats brute force?

Continue