KatInterview

Fewest Single-Letter Edits Through a Word List

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsbfsgraphstrings

Last updated

Tests modeling word edits as an implicit graph and running BFS with wildcard buckets to find the minimum number of one-letter changes, with careful edge cases.

Word Morphing Distance

You have a starting string start, a target string target of the same length, and a collection dictionary of distinct strings, all of the same length as well.

In one move you may change exactly one character of the current string to a different letter. The string you get after every move must be an entry of dictionary. You are done as soon as the current string equals target.

The starting string itself does not need to appear in dictionary.

Task

Return the smallest number of moves needed to turn start into target. Each single-character change counts as one move. If no sequence of valid moves exists, return -1.

Note that you are counting moves (edges in the path), not the number of strings in the path. For instance, hit -> hot -> dot -> dog -> cog is 4 moves.

Rules and edge cases

  • If start == target, the answer is 0, even if target is not in dictionary.
  • Otherwise, since the last move produces target, it must be in dictionary; if it is not, the answer is -1.
  • Two strings are one move apart exactly when they differ in exactly one position.

Input

  • start: the starting string.
  • target: the goal string.
  • dictionary: a list of distinct strings that intermediate and final strings must come from.

Output

An integer: the minimum number of moves, or -1 if the target cannot be reached.

Constraints

  • 1 <= len(start) = len(target) <= 20
  • 1 <= len(dictionary) <= 50000
  • All strings consist of lowercase English letters only.
  • All dictionary entries have the same length as start.

Examples

Example 1

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

Output: 4

Hints

Hint 1

Think of every string as a node, with an edge between two strings that differ in exactly one position. What algorithm gives shortest paths in an unweighted graph?

Hint 2

Comparing all pairs of dictionary words is too slow for 50,000 words. Group words by a pattern with one position replaced by a wildcard (for example `h*t`); words sharing a pattern are neighbors.

Hint 3

Mark strings as visited when you enqueue them, and remember that you count moves, not words on the path. Handle `start == target` and a missing `target` before running the search.