Python coding

Fewest letter changes between two words

You can turn one word into another by changing a single letter at a time, and every word you produce along the way, including the last, must be in the list words. Return the fewest changes needed to turn start into target, or -1 if it can't be done.

All words are lowercase and have the same length, and start differs from target. start doesn't need to be in words, which may contain repeats.

Besides the tests, one large input (16 four-letter words) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • fewest_changes("cold", "warm", ["cord","card","ward","warm","word"]) → 4
  • fewest_changes("cat", "dog", ["cot","cog","dot","dog"]) → 3
  • fewest_changes("lead", "gold", ["load","goad"]) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Model it as a graph: each word is a node, and two words are joined when they differ in exactly one letter. Fewest changes = shortest path.

Hint 2

All edges cost one change, so use BFS from start. To find neighbors, try every letter at every position and keep the results that are in a set of words.

Hint 3

Remove a word from the set the moment you queue it, so it is never queued twice. The first time target comes off the queue, its level is the answer.

Solution and why it works
pythonO(N·L²·26), N words of length L · O(N·L)
from collections import deque
from string import ascii_lowercase


def fewest_changes(start: str, target: str, words: list[str]) -> int:
    unused = set(words)
    if target not in unused:
        return -1
    unused.discard(start)
    queue = deque([(start, 0)])
    while queue:
        word, changes = queue.popleft()
        if word == target:
            return changes
        for i in range(len(word)):
            for ch in ascii_lowercase:
                nxt = word[:i] + ch + word[i + 1:]
                if nxt in unused:
                    unused.remove(nxt)           # visited when queued: each word enters once
                    queue.append((nxt, changes + 1))
    return -1

Words are nodes and a one-letter change is an edge, so the fewest changes is a shortest path in an unweighted graph: BFS. The graph is never built: for each word, try 26 letters at each of its L positions and look the result up in a set. Removing a word from the set when it is queued is the visited mark. DFS finds a chain but not the shortest, and heading straight for target fails when the only route first moves away from it.