Skip to the solution
MediumDSA15 min read

Word Ladder: shortest transformation via BFS — how do you build the wildcard graph?

228 views

The problem

Question presented to candidate: "In Word Ladder you BFS from a begin word to an end word, changing one letter per step, using only dictionary words. Instead of trying all 26 letters at every position, build a wildcard graph: group the words by patterns like h*t, and use those groups to find neighbours. Show how you build it and how the BFS uses it, in Python."

What a strong answer should cover:

  • The pattern idea: each word of length L yields L patterns (hot → *ot, h*t, ho*); two words are one letter apart iff they share a pattern.
  • Building pattern → [words] buckets in O(N · L²) time and memory, including beginWord.
  • BFS that looks up a word's L buckets for neighbours, marks visited on enqueue, and clears each bucket after scanning it so the whole search reads at most N · L entries.
  • Comparison with pairwise comparison (O(N² · L)) and with the 26-letter method (O(N · 26 · L²)), and the memory cost of the buckets.
  • Python specifics: collections.defaultdict(list) for building, .get(p, []) for reading so lookups do not insert empty buckets, and slicing w[:i] + "*" + w[i+1:] to make patterns.

Clarifying questions expected:

  • Are all words the same length, and is the dictionary reused for many queries?

Code / implementation expected: Yes — a Python build_buckets(words) with defaultdict(list) and a BFS ladder(begin, end, word_list) that uses and clears the buckets.

  • bfs
  • graph
  • Amazon

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.

PythonBuilding the wildcard buckets for the LeetCode list, then BFS through them
PythonPairwise comparison vs wildcard buckets, and BFS with vs without clearing buckets

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 112 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 nextMedium

Compare common sorting algorithms.

Continue