LeetCode #433 Medium

Minimum Genetic Mutation

Minimum Genetic Mutation is LeetCode 433 (Medium). A gene is an 8-character string of the letters A, C, G and T, and one mutation changes exactly one character. Return the fewest mutations that turn startGene into endGene, where every gene reached along the way, endGene included, must be in bank. Return -1 if it cannot be done.

  • startGene itself does not have to be in the bank.
  • The bank holds at most 10 genes, so the search is always small.
Constraints
  • 0 <= bank.length <= 10
  • startGene.length == endGene.length == bank[i].length == 8
  • startGene, endGene, and bank[i] consist of only the characters ['A', 'C', 'G', 'T'].
bfsimplicit-graphstrings
Open on LeetCode ↗
02

Intuition

Treat each gene as a node, with an edge between two genes that differ in exactly one character. Every mutation crosses one edge, so the answer is the shortest path from startGene to endGene, and BFS finds shortest paths when every edge counts as 1.

BFS works in rounds: first every gene one mutation away, then every gene two away, and so on. So the round in which endGene comes out of the queue is the minimum number of mutations.

The edges are never built in advance. From a gene, try the other 3 letters at each of the 8 positions, and keep only the results that are in the gene bank and not seen yet.

How to spot this pattern

"Fewest single changes from one string to another, through a list of allowed strings" is BFS on an implicit graph: the strings are nodes and a one-character change is an edge. Here the alphabet is only 4 letters long and every string is 8 characters.

03

Approach

Try it first

Before reading on, list every gene you can reach in one mutation from a given gene, and how many there are. Then decide what the search must remember so it never expands the same gene twice. Aim for a BFS that touches each bank gene at most once.

1

Put the bank in a set

Store the bank genes in a hash set so each lookup is O(1). If endGene is not in it, return -1 at once: the last mutation must land on a bank gene, so the target can never be reached.

2

Start from the start gene

Queue startGene, mark it as seen and set steps = 0. The start counts as zero mutations, and marking it seen stops the search from walking back to it.

3

Take one round at a time

Pop every gene that was in the queue when the round began. If one of them is endGene, return steps, because BFS reaches every gene in the fewest rounds possible.

4

Try every one-letter change

For each of the 8 positions and each letter in ACGT, build the changed gene. If it is in the bank and not seen, mark it seen and queue it for the next round. Marking it as it is queued means no gene is ever queued twice.

5

Count the round, or give up

After each round add 1 to steps and continue with the genes just queued. If the queue runs empty first, no chain of bank genes leads to endGene, so return -1.

04

Code in Python, C++ and Java

▶1from collections import deque
▶2 
▶3class Solution:
▶4 def minMutation(self, startGene, endGene, bank):
▶5 genes = set(bank)
▶6 if endGene not in genes:
▶7 return -1
▶8 queue = deque([startGene])
▶9 seen = {startGene}
▶10 steps = 0
▶11 while queue:
▶12 for _ in range(len(queue)):
▶13 gene = queue.popleft()
▶14 if gene == endGene:
▶15 return steps
▶16 for i in range(len(gene)):
▶17 for ch in "ACGT":
▶18 nxt = gene[:i] + ch + gene[i + 1:]
▶19 if nxt in genes and nxt not in seen:
▶20 seen.add(nxt)
▶21 queue.append(nxt)
▶22 steps += 1
▶23 return -1
genenothing popped yetone-letter changesACGTgene bankAACCGGTAtargetqueueAACCGGTTsteps0target is in the bank → start the search
queue[AACCGGTT]
steps0
The target AACCGGTA is in the bank, so a path may exist. The start gene goes into the queue at 0 mutations. It does not need to be in the bank itself; only the genes it mutates into do.
gene being expandedAACCGGTTone-letter changesAAACCCGGGTTTgene bankAACCGGTAtargetqueueemptysteps0AACCGGTT is not the target → try its changes
geneAACCGGTT0 mutations from the start
Take AACCGGTT from the front of the queue. It is not the target, so try changing each of its 8 letters to each of the other 3. The faded cells in the grid are its current letters, which would give back the same gene.
gene being expandedAACCGGTTone-letter changesAAAAAAAAACCCCCCCCCGGGGGGGGGTTTTTTTTTgene bankAACCGGTAtargetqueueemptysteps024 changes, 1 new bank gene
new1in the bank, not seen
Each grid cell is one change: column = position, row = new letter. The blue cell is a gene in the bank that has not been reached yet. Grey letters are genes not in the bank.
gene being expandedAACCGGTTone-letter changesAAAAAAAAACCCCCCCCCGGGGGGGGGTTTTTTTTTgene bankAACCGGTAtargetqueueAACCGGTAsteps0queue AACCGGTA (letter 8 becomes A)
queue[AACCGGTA]
AACCGGTA is one mutation from AACCGGTT, so it is 1 mutation from the start. Marking it seen now, as it is queued, stops another gene in this round from queuing it a second time.
generound finishedone-letter changesACGTgene bankAACCGGTAtargetqueueAACCGGTAsteps1round done → steps 1
steps1
queue[AACCGGTA]
Every gene 0 mutations away has been expanded. Everything in the queue now is exactly 1 mutation from the start.
gene being expandedAACCGGTAone-letter changesAAAACCCGGGTTgene bankAACCGGTAtargetqueueemptysteps1reached the target after 1 mutation
result1
The gene taken from the queue is the target. BFS handles every gene 0 mutations away before any gene 1 away, so no shorter chain exists. Return 1.
05

Common pitfalls

Requiring the start gene to be in the bank

✗ Wrong
if startGene not in genes or endGene not in genes:
    return -1
✓ Right
if endGene not in genes:
    return -1

Only the genes you mutate into must be in the bank. On the problem's first example, startGene = "AACCGGTT" with bank = ["AACCGGTA"], the extra check returns -1, but the answer is 1.

Counting the start gene as one step

✗ Wrong
queue = deque([startGene])
steps = 1
✓ Right
queue = deque([startGene])
steps = 0

This problem counts mutations, the changes between genes, not the genes in the chain. Starting at 1 returns 2 on that same first example, where one mutation is enough.

Searching without a seen set

✗ Wrong
if nxt in genes:
    queue.append(nxt)
✓ Right
if nxt in genes and nxt not in seen:
    seen.add(nxt)
    queue.append(nxt)

Two bank genes one change apart keep queuing each other. For startGene = "AACCGGTT", endGene = "TTTTTTTT", bank = ["AACCGGTA", "AACCGCTA", "TTTTTTTT"], the target is unreachable and the queue never empties, so the loop never ends.

06

Edge cases

startGene equals endGene

If endGene is in the bank, the first gene popped is the target and the answer is 0.

07

Complexity

Time
O(B · L²)
Space
O(B · L)
B is the bank size and L = 8 is the gene length. Each of the at most B + 1 genes expanded builds 3L changed genes, each of length L. The set, the seen set and the queue hold at most B + 1 genes.
08

Minimum Genetic Mutation vs Word Ladder

LeetCode 127 is the same BFS on a larger scale. The differences are all in the details:

ProblemLetters triedCountsNo pathSize
433 Minimum Genetic Mutation (this page)4: A C G Tmutations, so start at 0return -1at most 10 genes of length 8
127 Word Ladder26: a to zwords in the sequence, so start at 1return 0up to 5,000 words of length 10
09

Minimum Genetic Mutation FAQ

Can I compare each gene with every bank gene instead of generating changes?

Yes. Two genes are one mutation apart when exactly one of their 8 characters differs, and with at most 10 bank genes that check costs almost nothing. Generating the 24 changes and looking them up in a set scales better when the bank is large, as in Word Ladder.