Word Ladder solution explained

Word Ladder asks for the length of the shortest chain from a start word to a target word, changing one letter per step and using only words from a given list. Treat every word as a node and every one-letter change as an edge, then run breadth-first search from the start word; the first time the target comes off the queue, its distance is the answer. Grouping words by wildcard patterns such as "b_g" finds neighbors without comparing every pair.

By Published 9 min read

The problem, in plain terms

You are given a start word, a target word and a list of allowed words, all the same length and in lowercase. In one move you may change exactly one letter, and the new word must be in the allowed list. The start word itself does not have to be in the list. Return the number of words in the shortest sequence that begins with the start word and ends with the target, or 0 if the target cannot be reached.

start = "bat", target = "fog"
allowed = ["bot", "bog", "fog", "but", "fat"]
bat -> bot -> bog -> fog           answer: 4

start = "bat", target = "fog"
allowed = ["bot", "bog", "but", "fat"]
"fog" is not allowed                answer: 0
Two small puzzles, made up for this page

The answer counts words, not moves. The first ladder has three moves and four words, and the expected output is 4. That off-by-one is the most common slip on this problem, so say which one you are returning. In the second puzzle the target is missing from the list, so no ladder can end there, and you can return 0 before searching at all.

Clarify with the interviewer: are all words the same length? Are they lowercase letters only? Can the list contain duplicates? What should happen if start equals target? How many words and how long are they? The sizes decide which neighbor-finding method is cheaper.

What makes it an interview favorite

Nothing in the prompt says graph. The interviewer wants to see you notice that words are nodes, single-letter changes are edges, and shortest means breadth-first search. After that, the conversation moves to cost: building the graph naively is quadratic in the number of words, and a strong candidate finds a way around it. Bidirectional search is a common closing follow-up.

Slower approaches first

A depth-first search that tries every possible chain and keeps the shortest is correct but can explore an exponential number of paths. A big improvement is to build the graph explicitly: compare every pair of words, connect the pairs that differ in exactly one position, then run a breadth-first search. That comparison costs O(N² × L) for N words of length L, which is fine for a few hundred words and slow for tens of thousands.

from collections import deque


def ladder_length_pairs(start, target, words):
    nodes = list(dict.fromkeys([start] + words))
    if target not in words:
        return 0

    def one_apart(a, b):
        return sum(x != y for x, y in zip(a, b)) == 1

    adj = {w: [v for v in nodes if one_apart(w, v)] for w in nodes}
    steps = {start: 1}
    line = deque([start])
    while line:
        w = line.popleft()
        if w == target:
            return steps[w]
        for v in adj[w]:
            if v not in steps:
                steps[v] = steps[w] + 1
                line.append(v)
    return 0
Python: compare every pair to build the graph, then BFS. Correct, O(N² × L).

Optimal approach: BFS with wildcard buckets

Two words are neighbors exactly when they match after blanking out the same single position. So for every word and every position, compute a pattern with that letter replaced by an underscore, and file the word under it: "bog" goes into "_og", "b_g" and "bo_". Every bucket then holds a group of mutual neighbors. During the search, a word's neighbors are the contents of its L buckets, which avoids comparing it against the whole list.

from collections import defaultdict, deque


def ladder_length(start, target, words):
    allowed = set(words)
    if target not in allowed:
        return 0
    size = len(start)
    buckets = defaultdict(list)  # "b_g" -> every word that fits it
    for w in allowed | {start}:
        for i in range(size):
            buckets[w[:i] + "_" + w[i + 1:]].append(w)

    dist = {start: 1}
    queue = deque([start])
    while queue:
        word = queue.popleft()
        if word == target:
            return dist[word]
        for i in range(size):
            key = word[:i] + "_" + word[i + 1:]
            for nxt in buckets.pop(key, []):
                if nxt not in dist:
                    dist[nxt] = dist[word] + 1
                    queue.append(nxt)
    return 0
Python: breadth-first search where each wildcard bucket is used once and then discarded.

Popping each bucket after its first use is a small but real saving. Breadth-first search reaches every member of a bucket at the same distance the first time any member is expanded, so looking in that bucket again can never improve anything. Mark words as seen when they enter the queue, not when they leave it, or the same word can be queued several times from different neighbors.

A one-sided search fans out from the start, and the frontier can grow quickly. Searching from both ends at once and stopping when the two frontiers touch usually explores far fewer words, because two half-depth searches are smaller than one full-depth search. Always expand whichever frontier is smaller. This version finds neighbors by trying every other letter at every position, which is the better choice when the alphabet is small and the word list is large.

function ladderLength(start, target, words) {
  const allowed = new Set(words);
  if (!allowed.has(target)) return 0;
  if (start === target) return 1;
  const letters = "abcdefghijklmnopqrstuvwxyz";
  let near = new Set([start]);
  let far = new Set([target]);
  const used = new Set([start, target]);
  let length = 1; // words on a ladder joining the two frontiers, minus one
  while (near.size > 0 && far.size > 0) {
    if (near.size > far.size) [near, far] = [far, near];
    const grown = new Set();
    for (const word of near) {
      for (let i = 0; i < word.length; i++) {
        for (const ch of letters) {
          if (ch === word[i]) continue;
          const cand = word.slice(0, i) + ch + word.slice(i + 1);
          if (far.has(cand)) return length + 1;
          if (allowed.has(cand) && !used.has(cand)) {
            used.add(cand);
            grown.add(cand);
          }
        }
      }
    }
    near = grown;
    length++;
  }
  return 0;
}
JavaScript: two frontiers that grow toward each other; the smaller one is expanded each round.

Termination is where bidirectional code usually goes wrong. Check whether a generated word sits in the opposite frontier before checking whether it was already used, since the target and every word on the far side are marked as used. Keep the count consistent too: here length is the number of completed expansions on both sides plus one, so touching the far frontier adds one more word to it.

Complexity summary

N allowed words of length L; alphabet of 26 letters
ApproachTimeExtra space
DFS over every chainExponentialO(N) for the path
Compare all pairs, then BFSO(N² × L)O(N²) edges in the worst case
BFS with wildcard bucketsO(N × L²): N × L patterns, each built in O(L)O(N × L²) for the bucket keys
BFS trying each letter at each positionO(N × 26 × L²)O(N × L)
Bidirectional BFSSame worst case; usually far fewer words expandedO(N × L)
N allowed words of length L; alphabet of 26 letters. Scroll sideways on a small screen.

Edge cases to try

  • The target is not in the list: 0, without searching.
  • The start is one change from the target: 2.
  • The start word is also in the list: it must not be counted twice or revisited.
  • Several shortest ladders exist: any length-correct answer is fine.
  • Every word differs from the target in every position, so no ladder exists: 0 after the search runs dry.
  • Duplicate words in the list: the set takes care of them.

Mistakes to avoid

  • Returning the number of moves instead of the number of words.
  • Using depth-first search and returning the first ladder it finds, which may not be the shortest.
  • Marking words as visited when they leave the queue, so they are queued many times.
  • Removing words from the shared dictionary in a way that also deletes the target before it is reached in the bidirectional version.
  • Building every candidate string inside the innermost loop without noticing it costs O(L) each, then quoting O(N × L) time.

Follow-ups

  • Return one shortest ladder. Store each word's parent when it is first reached, then walk back from the target.
  • Return every shortest ladder. Run BFS level by level, record all parents from the previous level rather than just the first, then backtrack. The number of ladders can grow very fast, so mention the output size.
  • Allow inserting or deleting a letter too. Neighbors become words within edit distance one; wildcard patterns can be extended with a pattern per gap position.
  • Answer many queries against one dictionary. Build the buckets once and reuse them for every search.

How to explain it out loud

Fictional example

From words to a graph in one minute
Candidate
Each word is a node, and two words are linked if they differ in one letter. The shortest ladder is the shortest path, and the edges have no weights, so breadth-first search is the right tool.
Candidate
Comparing every pair to build edges is quadratic. Instead I file each word under wildcard patterns like b_g. Words in the same bucket are neighbors, so finding a word's neighbors costs about L squared.
Candidate
I count words, not moves, so the start gets distance 1. If the target is not in the list I return 0 straight away.
Interviewer
Can we make it faster?
Candidate
Search from both ends and always grow the smaller frontier. The worst case is the same, but it usually explores much less of the dictionary.

Network Delay Time is the weighted version of shortest paths, where breadth-first search is no longer enough. Cheapest Flights Within K Stops adds a limit on the number of steps. Number of Connected Components uses a similar graph built from a list, but asks a connectivity question instead of a distance one. For the general background, see the data structure interview questions guide.

How Natively fits into practice

Word Ladder is a good test of whether you can recognize a hidden graph quickly. While you practice on Mac or Windows, Natively can read the puzzle from a screenshot and outline an approach, for instance breadth-first search with wildcard buckets, and point out the words-versus-moves count. It also keeps a transcript of the mock round, so you can check whether you justified BFS over DFS before writing code. The AI interview assistant page explains the setup.

Questions people ask

How do you solve Word Ladder?

Treat words as nodes and one-letter changes as edges, then run breadth-first search from the start word. Find neighbors through wildcard buckets such as b_g instead of comparing every pair. Return the target's distance counted in words, or 0 if it is never reached.

Why is BFS used for Word Ladder instead of DFS?

The edges have no weights, so breadth-first search reaches each word first along a shortest chain. Depth-first search can find a ladder, but not necessarily the shortest one without exploring every path.

What is the time complexity of Word Ladder?

With N words of length L, BFS with wildcard buckets is O(N × L²), because each word yields L patterns that each take O(L) to build. Comparing every pair of words is O(N² × L).

Does the Word Ladder answer count steps or words?

Words. A ladder with three letter changes has four words, including the start and the target. If the target is not in the allowed list, the answer is 0.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP