Minimum Genetic Mutation (LeetCode 433): Solution and Explanation

Medium
Hash Table
String
Breadth First Search

Change an 8-letter gene one letter at a time, where every intermediate gene must be in the bank. Find the fewest changes needed to reach the end gene, or -1.

Intuition

Think of every gene as a node. Two genes are connected when they differ in exactly one position, because one mutation turns one into the other.

The number of mutations along a route is the number of edges, and every edge costs the same. The fewest mutations is therefore a shortest path in an unweighted graph, which is exactly what breadth-first search finds.

BFS explores genes in order of how many mutations they need. The first time the end gene comes off the queue, no shorter route can exist.

Approach: Breadth-first search over the bank

  1. Put (startGene, 0) in a queue and mark startGene as seen.
  2. Pop the next gene and its step count. If it equals endGene, return the step count.
  3. Compare it with every bank gene that has not been seen yet, counting the positions where they differ.
  4. If they differ in exactly one position, mark the bank gene seen and enqueue it with steps + 1.
  5. If the queue runs out, endGene is unreachable: return -1.

Step-by-step example

startGene = "AACCGGTT", endGene = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"]
  1. Pop AACCGGTT at step 0. AACCGGTA differs only in the last letter, so it is enqueued at step 1. AACCGCTA differs in 2 positions and AAACGGTA in 2, so neither is one mutation away.
  2. Pop AACCGGTA at step 1. AACCGCTA differs only at position 5 and AAACGGTA only at position 2, so both are enqueued at step 2.
  3. Pop AACCGCTA at step 2. It is not the end gene and every bank gene is already seen.
  4. Pop AAACGGTA at step 2. It is the end gene, so the answer is 2.

Code: Python, Java, C++

1class Solution:
2    def minMutation(self, startGene: str, endGene: str, bank: List[str]) -> int:
3        queue = [(startGene, 0)]
4        seen = {startGene}
5        head = 0
6        while head < len(queue):
7            gene, steps = queue[head]
8            head += 1
9            if gene == endGene:
10                return steps
11            for nxt in bank:
12                if nxt in seen:
13                    continue
14                diff = sum(1 for a, b in zip(gene, nxt) if a != b)
15                if diff == 1:
16                    seen.add(nxt)
17                    queue.append((nxt, steps + 1))
18        return -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(B^2 * L)

Each of the B + 1 genes is popped at most once and compared with up to B bank genes, each comparison costing L = 8 steps.

Space

O(B)

The queue and the seen set each hold at most B + 1 genes.

Other approaches

Generate neighbours letter by letter (time O(B * L * 4), space O(B))

For each position try the other 3 letters and look the result up in a set of bank genes. That is 24 lookups per gene and scales better when the bank is large.

Bidirectional BFS (time O(B * L * 4), space O(B))

Search from both ends and stop when the frontiers meet. It reduces the explored area on big graphs but is unnecessary with at most 10 bank genes.

Depth-first search with backtracking (time O(B!), space O(B))

Explore every route and keep the shortest. It is correct but can explore many long routes before the short one, so BFS is the natural fit.

Common mistakes

  • Marking genes as seen when they are popped instead of when they are pushed lets the same gene enter the queue several times.
  • Every intermediate gene must be in the bank. Counting a route through a gene that is not in the bank gives an answer that is too small.
  • The start gene does not need to be in the bank, but the end gene does. If the end gene is missing from the bank the answer is -1, unless it equals the start gene.

Frequently asked questions

Why BFS and not DFS?

Every mutation counts as one step, so the graph is unweighted. BFS visits genes in order of distance from the start, so the first time it reaches the end gene it has used the fewest mutations.

Why compare against every bank gene instead of generating neighbours?

The bank has at most 10 genes, so comparing the current gene with each one is about as cheap as trying all 24 single-letter changes, and it is simpler to write.

How is this related to Word Ladder?

It is the same problem on a smaller alphabet: words become genes and the dictionary becomes the bank. Word Ladder counts words in the sequence, while this problem counts mutations, which is one fewer.