Typorithm · hard

Word Ladder

word-laddergraphsimplicit-graphbfs-shortestneighbor-gen
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Word Ladder

0%

Graphs

BFS over an implicit graph where words connect if they differ by one letter; the first time endWord appears gives the shortest ladder.

Words are nodes; an edge joins two words that differ by exactly one letter.

BFS from beginWord level by level finds the shortest transformation sequence.

Neighbors are generated by swapping each position through a-z and checking the word set, deleting visited words.

01

Implicit graph: one-letter-apart edges.

02

BFS gives the shortest ladder.

03

Generate neighbors via a-z swaps.

function ladderLength(beginWord, endWord, wordList) {
  const words = new Set(wordList);
  if (!words.has(endWord)) {
    return 0;
  }

  let queue = [beginWord];
  let steps = 1;

  while (queue.length > 0) {
    const next = [];
    for (const word of queue) {
      if (word === endWord) {
        return steps;
      }
      for (let i = 0; i < word.length; i += 1) {
        for (let c = 97; c <= 122; c += 1) {
          const candidate = word.slice(0, i) + String.fromCharCode(c) + word.slice(i + 1);
          if (words.has(candidate)) {
            words.delete(candidate);
            next.push(candidate);
          }
        }
      }
    }
    queue = next;
    steps += 1;
  }

  return 0;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Word set

A Set gives O(1) membership and visited-removal.

const words = new Set(wordList)

2. Next BFS level

Process one transformation level per step.

const next = []

3. Generate neighbors

Change each position to every letter a-z.

const candidate = word.slice(0, i) + String.fromCharCode(c) + word.slice(i + 1)

4. Mark visited

Removing from the set prevents revisiting a word.

words.delete(candidate)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Word Ladder: Lesson & Practice · Typorithm | ApplyDjinn