Leetcode 433: Minimum Genetic Mutation

grid47
grid47
Exploring patterns and algorithms
Sep 24, 2024 7 min read

A series of genes evolving through mutations, with each valid mutation softly glowing as it occurs.
Solution to LeetCode 433: Minimum Genetic Mutation Problem

You are given two gene strings, startGene and endGene, both consisting of 8 characters. You also have a gene bank of valid gene strings that can be mutated into one another. A mutation is defined as changing one character at a time, and the mutated gene string must exist in the gene bank. Your task is to determine the minimum number of mutations needed to transform startGene into endGene. If transformation is impossible, return -1.
Problem
Approach
Steps
Complexity
Input: You are given three inputs: `startGene` (an 8-character gene string), `endGene` (an 8-character gene string), and a `bank` (a list of valid gene strings).
Example: startGene = 'AACCGGTT', endGene = 'AACCGGTA', bank = ['AACCGGTA']
Constraints:
• 0 <= bank.length <= 10
• startGene.length == endGene.length == bank[i].length == 8
• startGene, endGene, and bank[i] consist of only the characters ['A', 'C', 'G', 'T']
Output: Return the minimum number of mutations needed to transform `startGene` to `endGene`. If it's not possible, return -1.
Example: 1
Constraints:
• If no mutation path exists, return -1.
Goal: The goal is to find the shortest path from `startGene` to `endGene` by performing valid mutations and using the gene bank.
Steps:
• 1. Check if `endGene` exists in the gene bank. If not, return -1.
• 2. Use a breadth-first search (BFS) to explore all possible gene strings starting from `startGene`.
• 3. For each gene string, generate all possible mutations by changing one character at a time.
• 4. If a mutated gene string exists in the gene bank, add it to the BFS queue.
• 5. Keep track of the number of mutations, and return the result when `endGene` is reached.
Goal: The solution should handle cases with small to moderate bank sizes and up to 10 valid mutations.
Steps:
• The length of the gene bank is between 0 and 10.
• All gene strings are 8 characters long and consist of the characters ['A', 'C', 'G', 'T'].
Assumptions:
• The startGene is always valid.
• Mutations are only allowed if the resulting gene string exists in the bank.
Input: Input: startGene = 'AACCGGTT', endGene = 'AACCGGTA', bank = ['AACCGGTA']
Explanation: We mutate the last character from 'T' to 'A', which results in the endGene after one mutation.

Input: Input: startGene = 'AACCGGTT', endGene = 'AAACGGTA', bank = ['AACCGGTA','AACCGCTA','AAACGGTA']
Explanation: The solution involves two mutations: first from 'AACCGGTT' to 'AACCGGTA', and then from 'AACCGGTA' to 'AAACGGTA'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus