SDE & MLE Prep

433. Minimum Genetic Mutation

Problem

A gene is an 8-character string over A, C, G, T; one mutation changes one character. Every gene you pass through (including the end) must be in bank. Return the minimum mutations from startGene to endGene, or −1 if impossible.

Example: startGene = "AACCGGTT", endGene = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"] → 2

Same as Word Ladder with a 4-letter alphabet: BFS over valid genes in the bank.

Complexity: O(B · 8 · 4).

class Solution:
    def minMutation(self, startGene: str, endGene: str, bank: List[str]) -> int:
        valid = set(bank)
        q, seen, steps = deque([startGene]), {startGene}, 0
        while q:
            for _ in range(len(q)):
                g = q.popleft()
                if g == endGene:
                    return steps
                for i in range(len(g)):
                    for ch in "ACGT":
                        nxt = g[:i] + ch + g[i + 1:]
                        if nxt in valid and nxt not in seen:
                            seen.add(nxt)
                            q.append(nxt)
            steps += 1
        return -1