Minimum Genetic Mutation
LeetCode 433 · Medium · solution, intuition & step-by-step walkthrough
BFS over one-letter mutations in the bank.
This is how I solved Minimum Genetic Mutation (LeetCode 433), a medium problem from the State-Space BFS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Each gene is a node; a valid one-letter change to a gene in the bank is an edge. The fewest mutations is the shortest path, found with BFS.
Approach
- 1
Queue (start, 0).
- 2
Pop; if it's the end gene, return steps.
- 3
Try every position × every letter; enqueue unvisited bank genes.
How I solved it
BFSPythonO(B·L) time
class Solution:
def minMutation(self, startGene: str, endGene: str, bank: List[str]) -> int:
q = deque([(startGene,0)])
visited = set()
while q:
word,steps = q.popleft()
if word==endGene:
return steps
for i in range(len(word)):
for char in ("A","C","G","T"):
new_word = word[:i]+char+word[i+1:]
if new_word in bank and new_word not in visited:
visited.add(new_word)
q.append((new_word,steps+1))
return -1
Minimum Genetic Mutation — FAQ
What is the intuition behind Minimum Genetic Mutation?
Each gene is a node; a valid one-letter change to a gene in the bank is an edge. The fewest mutations is the shortest path, found with BFS.
How do you solve Minimum Genetic Mutation (LeetCode 433)?
1. Queue (start, 0). 2. Pop; if it's the end gene, return steps. 3. Try every position × every letter; enqueue unvisited bank genes.
What is the time and space complexity of Minimum Genetic Mutation?
Time: O(B · L · 4). Space: O(B). (Accepted approach: BFS.)
What are common mistakes in Minimum Genetic Mutation?
Use a set for the bank — list membership is O(B).