KatInterview

Shortest Word Chain Allowing One or Two Letter Swaps

Trees & GraphsAuto-graded · 24 test cases
MediumAuto-gradedTrees & Graphsbfsshortest-pathstrings

Last updated

Find a shortest word chain where each step swaps one or two letters, with a fixed tie-break, using BFS on an implicit graph and wildcard bucketing for fast neighbor lookup.

You are given a starting word, a target word, and a list of allowed words. All words are lowercase. Build a chain of words that begins at the starting word and ends at the target word, moving one word at a time.

Move rule. Going from one word to the next replaces the letters at exactly 1 or 2 positions. The two words must have the same length and differ in exactly 1 or 2 positions. Letters cannot be inserted or removed.

Allowed words.

  • Every word in the chain other than the starting word must come from the allowed list, with one exception: the target word is always allowed as the final word, even if the list does not contain it.
  • The starting word does not need to appear in the list.
  • Words in the list whose length differs from the starting word's length are ignored. The list may contain duplicates, which have no effect.

Goal. Return a chain with the fewest possible moves, as a list of words from the starting word to the target word, both included.

Special cases.

  • If the starting word equals the target word, return a list containing just that word, whatever the list holds.
  • If the starting and target words have different lengths, or no chain exists, return an empty list.

Which chain to return. Several shortest chains may exist, and the answer is the one produced by this exact procedure:

  1. Run a breadth-first search from the starting word with a FIFO queue.
  2. When a word is taken from the queue, look at all not-yet-discovered words that can be reached from it in one move. Handle them in ascending alphabetical (lexicographic) order.
  3. Each newly discovered word records the word it was discovered from as its predecessor. A word is never re-assigned a predecessor.
  4. The returned chain is the one obtained by following predecessors back from the target word.

Following these rules gives a single well-defined answer for every input.

Function. Return the chain as List[str].

Constraints

  • Words contain only lowercase English letters a-z.
  • Word lengths are small (about 1 to 10 characters).
  • The list can hold up to roughly 10^4 words.
  • The starting word may or may not be in the list.
  • The target word may or may not be in the list.
  • The list may be empty.

Examples

Example 1

Input: find_shortest_word_chain('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log', 'cog'])

Output: ['hit', 'dot', 'cog']

Example 2

Input: find_shortest_word_chain('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log'])

Output: ['hit', 'dot', 'cog']

Example 3

Input: find_shortest_word_chain('aaa', 'bbb', ['aab', 'abb', 'aba', 'bbb'])

Output: ['aaa', 'aab', 'bbb']

Example 4

Input: find_shortest_word_chain('same', 'same', [])

Output: ['same']

Hints

Hint 1

Treat each word as a node in an unweighted graph, with an edge between two words of equal length that differ in exactly 1 or 2 positions. A shortest path in an unweighted graph is a BFS job.

Hint 2

Comparing every pair of words is too slow. Replace two positions of a word with a wildcard to make patterns. Two distinct words share such a pattern exactly when they differ in at most 2 positions. Index words by these patterns, and use a single wildcard when the word length is 1.

Hint 3

To get the required tie-break, collect all neighbors of the dequeued word, sort them, and only then assign predecessors to the undiscovered ones. Rebuild the chain by walking predecessors back from the target and reversing. Handle equal start and target, and length mismatch, before the search.