CodeArchon

hardGraphsFacebookAmazonLinkedIn

Word-Ladder Transformer

A spelling game morphs one word into another by changing one letter at a time; each intermediate must come from a given dictionary.

Given beginWord, endWord, and a wordList, return the length of the shortest transformation sequence, or 0 if none.

Choose approach

hit
0
cur
hot
1
dot
2
dog
3
lot
4
log
5
cog
6
SetQueue (0)
empty
1/8
Narrationstep 1 of 8

Dequeue "hit" at depth 1.

1from collections import deque
2def ladderLength(begin, end, wordList):
3 S = set(wordList)
4 if end not in S: return 0
5 q = deque([(begin, 1)])
6 while q:
7 w, d = q.popleft()
8 if w == end: return d
9 for i in range(len(w)):
10 for c in 'abcdefghijklmnopqrstuvwxyz':
11 nxt = w[:i] + c + w[i+1:]
12 if nxt in S:
13 S.discard(nxt); q.append((nxt, d + 1))
14 return 0
Variables
word=hit
depth=1
queue=0

How to think about it

  1. BFS depth = ladder length.
  2. Delete visited words from the dictionary to avoid loops.
  3. Bidirectional BFS halves the search tree in practice.

Edge cases to catch in interview

  • endWord not in list -> 0.
  • beginWord == endWord usually constrained away.

Examples

Example 15
{"begin":"hit","end":"cog","wordList":["hot","dot","dog","lot","log","cog"],"values":["hit","hot","dot","dog","lot","log","cog"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed