LeetCode 433: Minimum Genetic Mutation — Python Solution

Solve LeetCode 433: Minimum Genetic Mutation in Python with a single-character BFS approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicGraph BFS
Reusable patternsingle-character BFS
ComplexityO(BL) practical time and O(B) space

What the problem is testing

BFS through valid bank strings formed by replacing one position with A, C, G, or T.

Algorithm

  1. BFS through valid bank strings formed by replacing one position with A, C, G, or T.
  2. Maintain this invariant: Every queued gene is valid and reached in the minimum number of mutations.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def minMutation(self, startGene, endGene, bank):
        if startGene == endGene: return 0
        allowed = set(bank)
        if endGene not in allowed: return -1
        queue = deque([(startGene, 0)]); seen = {startGene}
        for_queue = "ACGT"
        while queue:
            gene, steps = queue.popleft()
            for i in range(len(gene)):
                for base in for_queue:
                    candidate = gene[:i] + base + gene[i + 1:]
                    if candidate == endGene: return steps + 1
                    if candidate in allowed and candidate not in seen:
                        seen.add(candidate); queue.append((candidate, steps + 1))
        return -1

Why this is correct

The proof follows the maintained state: Every queued gene is valid and reached in the minimum number of mutations. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(BL) practical time and O(B) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

If the end gene is absent from the bank it is unreachable unless it already equals the start.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 909. Snakes and Ladders · Next: 127. Word Ladder