#433
Minimum Genetic Mutation
MediumHash TableStringBreadth-First SearchBreadth-First SearchGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * m)Space O(n)
The optimal approach uses Breadth-First Search (BFS) to explore the shortest path from the startGene to the endGene. This ensures that we find the minimum number of mutations efficiently by exploring all possibilities level by level.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a queue and add the startGene along with a mutation count of 0.
- 2Step 2: Use a set to keep track of visited genes to avoid cycles.
- 3Step 3: While the queue is not empty, dequeue the current gene and check if it matches the endGene.
- 4Step 4: If it matches, return the mutation count; otherwise, generate all valid mutations and enqueue them if they haven't been visited.
- 5Step 5: If the queue is exhausted without finding the endGene, return -1.
solution.py21 lines
1# Full working Python code
2from collections import deque
3
4def minMutation(startGene, endGene, bank):
5 if endGene not in bank:
6 return -1
7 bank_set = set(bank)
8 queue = deque([(startGene, 0)])
9 visited = set([startGene])
10 while queue:
11 current, mutations = queue.popleft()
12 if current == endGene:
13 return mutations
14 for i in range(len(current)):
15 for char in 'ACGT':
16 if current[i] != char:
17 mutation = current[:i] + char + current[i+1:]
18 if mutation in bank_set and mutation not in visited:
19 visited.add(mutation)
20 queue.append((mutation, mutations + 1))
21 return -1ℹ
Complexity note: The time complexity is O(n * m) where n is the number of genes in the bank and m is the length of the gene strings (which is constant at 8). Each gene can generate up to 32 mutations (4 choices for each of the 8 positions).
- 1BFS is effective for shortest path problems in unweighted graphs.
- 2Using a set for the bank allows O(1) lookups.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.