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, includingbeginWord. - 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 slicingw[: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.