433. Minimum Genetic Mutation
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the minimum number of single-character mutations to transform a startGene into an endGene. A crucial constraint is that any intermediate gene in this transformation sequence must exist in a given bank of valid genes. This problem can be perfectly modeled as finding the shortest path in an unweighted graph.
Solution
Minimum Genetic Mutation in Python
class Solution:
def minMutation(self, startGene: str, endGene: str, bank: List[str]) -> int:
# If start and end are the same, 0 mutations are needed.
if startGene == endGene:
return 0
# Convert bank to a set for efficient lookup.
bank_set = set(bank)
# If endGene is not in the bank, it's impossible to reach.
if endGene not in bank_set:
return -1
# Characters for mutation.
choices = ['A', 'C', 'G', 'T']
# BFS setup
queue = collections.deque([startGene])
visited = {startGene}
mutations = 0
while queue:
level_size = len(queue)
mutations += 1
for _ in range(level_size):
current_gene = queue.popleft()
# Try mutating each character in the current gene.
for i in range(len(current_gene)):
for char_choice in choices:
# Create the new gene string
next_gene = current_gene[:i] + char_choice + current_gene[i+1:]
if next_gene == current_gene:
continue
# If we found the endGene, return the number of mutations.
if next_gene == endGene:
return mutations
# If the new gene is in the bank and not visited, add to queue.
if next_gene in bank_set and next_gene not in visited:
visited.add(next_gene)
queue.append(next_gene)
# If queue becomes empty and we haven't found the endGene, it's unreachable.
return -1
Minimum Genetic Mutation in Java
class Solution {
public int minMutation(String startGene, String endGene, String[] bank) {
// If start and end are the same, 0 mutations are needed.
if (startGene.equals(endGene)) {
return 0;
}
// Convert bank to a set for efficient lookup.
Set<String> bankSet = new HashSet<>(Arrays.asList(bank));
// If endGene is not in the bank, it's impossible to reach.
if (!bankSet.contains(endGene)) {
return -1;
}
// Characters for mutation.
char[] choices = {'A', 'C', 'G', 'T'};
// BFS setup
Queue<String> queue = new LinkedList<>();
queue.offer(startGene);
Set<String> visited = new HashSet<>();
visited.add(startGene);
int mutations = 0;
while (!queue.isEmpty()) {
int levelSize = queue.size();
mutations++;
for (int i = 0; i < levelSize; i++) {
String currentGeneStr = queue.poll();
char[] currentGene = currentGeneStr.toCharArray();
// Try mutating each character in the current gene.
for (int j = 0; j < currentGene.length; j++) {
char originalChar = currentGene[j];
for (char c : choices) {
if (c == originalChar) continue;
currentGene[j] = c;
String nextGene = new String(currentGene);
// If we found the endGene, return the number of mutations.
if (nextGene.equals(endGene)) {
return mutations;
}
// If the new gene is in the bank and not visited, add to queue.
if (bankSet.contains(nextGene) && !visited.contains(nextGene)) {
visited.add(nextGene);
queue.offer(nextGene);
}
}
// Restore original character for next position's mutation.
currentGene[j] = originalChar;
}
}
}
// If queue becomes empty and we haven't found the endGene, it's unreachable.
return -1;
}
}
Minimum Genetic Mutation in C++
class Solution {
public:
int minMutation(string startGene, string endGene, vector<string>& bank) {
// If start and end are the same, 0 mutations are needed.
if (startGene == endGene) {
return 0;
}
// Convert bank to a set for efficient lookup.
unordered_set<string> bankSet(bank.begin(), bank.end());
// If endGene is not in the bank, it's impossible to reach.
if (bankSet.find(endGene) == bankSet.end()) {
return -1;
}
// Characters for mutation.
char choices[] = {'A', 'C', 'G', 'T'};
// BFS setup
queue<string> q;
q.push(startGene);
unordered_set<string> visited;
visited.insert(startGene);
int mutations = 0;
while (!q.empty()) {
int levelSize = q.size();
mutations++;
for (int i = 0; i < levelSize; ++i) {
string currentGene = q.front();
q.pop();
// Try mutating each character in the current gene.
for (int j = 0; j < currentGene.length(); ++j) {
char originalChar = currentGene[j];
for (char c : choices) {
if (c == originalChar) continue;
currentGene[j] = c;
// If we found the endGene, return the number of mutations.
if (currentGene == endGene) {
return mutations;
}
// If the new gene is in the bank and not visited, add to queue.
if (bankSet.count(currentGene) && visited.find(currentGene) == visited.end()) {
visited.insert(currentGene);
q.push(currentGene);
}
}
// Restore original character for next position's mutation.
currentGene[j] = originalChar;
}
}
}
// If queue becomes empty and we haven't found the endGene, it's unreachable.
return -1;
}
};
Minimum Genetic Mutation in TypeScript
function minMutation(startGene: string, endGene: string, bank: string[]): number {
// If start and end are the same, 0 mutations are needed.
if (startGene === endGene) {
return 0;
}
// Convert bank to a set for efficient lookup.
const bankSet = new Set(bank);
// If endGene is not in the bank, it's impossible to reach.
if (!bankSet.has(endGene)) {
return -1;
}
// Characters for mutation.
const choices = ['A', 'C', 'G', 'T'];
// BFS setup
const queue: string[] = [startGene];
const visited = new Set<string>([startGene]);
let mutations = 0;
while (queue.length > 0) {
const levelSize = queue.length;
mutations++;
for (let i = 0; i < levelSize; i++) {
const currentGene = queue.shift()!; // Non-null assertion as queue.length > 0
// Try mutating each character in the current gene.
for (let j = 0; j < currentGene.length; j++) {
for (const charChoice of choices) {
if (charChoice === currentGene[j]) {
continue;
}
// Create the new gene string
const nextGene = currentGene.substring(0, j) + charChoice + currentGene.substring(j + 1);
// If we found the endGene, return the number of mutations.
if (nextGene === endGene) {
return mutations;
}
// If the new gene is in the bank and not visited, add to queue.
if (bankSet.has(nextGene) && !visited.has(nextGene)) {
visited.add(nextGene);
queue.push(nextGene);
}
}
}
}
}
// If queue becomes empty and we haven't found the endGene, it's unreachable.
return -1;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.