Question presented to candidate: "Given a begin word, an end word and a list of dictionary words, find the number of words in the shortest transformation sequence from begin to end, where each step changes exactly one letter and every intermediate word must be in the list. Return 0 if there is no such sequence. Please code it in Python."
What a strong answer should cover:
- Modelling: words are nodes, one-letter changes are edges, and the graph is implicit β generated on demand, not stored.
- BFS because every edge has the same cost, so the first time
endis reached is the shortest chain; the answer counts words, not steps. - Neighbour generation: 26 letters Γ L positions, kept only if the candidate is in a
set; mark visited when queued (e.g. by removing from the set). - Complexity O(N Β· 26 Β· LΒ²) time and O(N Β· L) space, and why comparing all pairs, O(NΒ² Β· L), is worse for large N.
- Python specifics:
set(notlist) for membership,collections.deque,string.ascii_lowercase, and the O(L) cost ofword[:i] + ch + word[i+1:]because strings are immutable. Bidirectional BFS as the follow-up optimisation.
Clarifying questions expected:
- Count words or steps? Must
endWordbe in the list? - Do you want the sequence itself, or all shortest sequences?
Code / implementation expected: Yes β a ladder_length(begin, end, word_list) in Python using BFS with a set, ideally also returning the chain via a parent map.