Minimum Genetic Mutation

A gene string has 8 characters, each one of A, C, G or T. One mutation changes exactly one character. Every intermediate gene, and the end gene, must be in the bank. Given startGene, endGene and bank, return the minimum number of mutations needed to turn startGene into endGene, or -1 if it cannot be done.

30:00

Minimum Genetic Mutation
medium
Free written solution
Topics
Companies

A gene string has 8 characters, each one of A, C, G or T. One mutation changes exactly one character. Every intermediate gene, and the end gene, must be in the bank. Given startGene, endGene and bank, return the minimum number of mutations needed to turn startGene into endGene, or -1 if it cannot be done.

Example 1:
Input: {"startGene":"AACCGGTT","endGene":"AAACGGTA","bank":["AACCGGTA","AACCGCTA","AAACGGTA"]}
Output: 2
Constraints:
  • 0≤bank.length≤100 \leq \text{bank.length} \leq 10

  • startGene.length=endGene.length=bank[i].length=8\text{startGene.length} = \text{endGene.length} = \text{bank}[i]\text{.length} = 8

  • startGene, endGene and bank[i] contain only the characters A, C, G and T.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"startGene":"AACCGGTT","endGene":"AAACGGTA","bank":["AACCGGTA","AACCGCTA","AAACGGTA"]}

Breadth-first search from AACCGGTT. Each bank gene that differs from the current gene in exactly one letter is one mutation away. The first time AAACGGTA comes off the queue, its step count is the minimum.

start

A

A

C

C

G

G

T

T

end

A

A

A

C

G

G

T

A

queue (dim = already popped)

A

A

C

C

G

G

T

T

0

bank (number = step it was reached at)

A

A

C

C

G

G

T

A

-

A

A

C

C

G

C

T

A

-

A

A

A

C

G

G

T

A

-

Variables
VariableValue
startGeneAACCGGTT
endGeneAAACGGTA
bank3
DepthFunction Call
Stack empty
0/14