Minimum Genetic Mutation
MediumTop Interview 150 GraphsXProblem
A gene is a string of 8 letters, each one of A, C, G or T. A mutation
changes exactly one letter of a gene. A mutation is only allowed if the gene it produces is in the given bank
(the start gene does not have to be in the bank).
Return the smallest number of mutations that turn startGene into endGene, or -1 if it cannot be done.
Constraints
- startGene and endGene have length 8; every bank entry has length 8
- All letters are A, C, G or T
- 0 ≤ bank.length ≤ 10
Examples: pick one to animate
Solutions
Time: Each gene enters the queue at most once, and for each one we build L × 4 candidate strings of length L and hash each in O(L); with L fixed at 8 the total is O(B).
Space: The bank set, the distance map and the queue each hold at most B + 1 genes of length L.
Think of every valid gene as a node, with a line between genes that differ in one letter. The fewest mutations is the shortest path from the start, and BFS finds shortest paths in an unweighted graph. For the gene at the front of the queue, build every string that differs in one position, and keep those that are in the bank and have not been reached yet. The first time the end gene comes out of the queue, its stored distance is the answer.