LC433 - Minimum Genetic Mutation

Description

A gene string can be represented by an 8-character long string, with choices from ‘A’, ‘C’, ‘G’, and ‘T’.
Suppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string.
For example, “AACCGGTT” –> “AACCGGTA” is one mutation.
There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string.
Given the two gene strings start and end and the gene bank bank, return the minimum number of mutations needed to mutate from start to end. If there is no such a mutation, return -1.
Note that the starting point is assumed to be valid, so it might not be included in the bank.

Example 1:

1
2
Input: start = "AACCGGTT", end = "AACCGGTA", bank = ["AACCGGTA"]
Output: 1

Example 2:

1
2
Input: start = "AACCGGTT", end = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"]
Output: 2

Example 3:

1
2
Input: start = "AAAAACCC", end = "AACCCCCC", bank = ["AAAACCCC","AAACCCCC","AACCCCCC"]
Output: 3

Constraints:

1
2
3
4
5
start.length == 8
end.length == 8
0 <= bank.length <= 10
bank[i].length == 8
start, end, and bank[i] consist of only the characters ['A', 'C', 'G', 'T'].

Solution

This question is very similar to [127]
If end is not in the bank, return -1 directly

  • Store start in the queue, because there are only four letters of ACGT, so traverse the gene sequence and change one of the letters. If the changed letter is not in visited, put it in the queue
  • If the changed letter is equal to the value of end, return to step
  • If no matching gene is found, return -1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# O(nm) time | O(nm) space
from collections import deque
class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
if end not in bank:
return -1

queue = deque([(start,0)])
visited = set({start})
while queue:
cur, step = queue.popleft()
if cur == end:
return step
for i in range(8):
for j in ["A","C","G", "T"]:
nxt = cur[:i]+j+cur[i+1:]
if nxt in bank and nxt not in visited:
queue.append((nxt, step+1))
visited.add(nxt)
return -1