Minimum Genetic Mutation LeetCode Solution

Last updated on February 28th, 2025 at 12:55 pm

Here, we see a Minimum Genetic Mutation LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

String

Companies

Twitter

Level of Question

Medium

Minimum Genetic Mutation LeetCode Solution

Minimum Genetic Mutation LeetCode Solution

1. Problem Statement

A gene string can be represented by an 8-character long string, with choices from ‘A’, ‘C’, ‘G’, and ‘T’.

Suppose we need to investigate a mutation from a gene string startGene to a gene string endGene where one mutation is defined as one single character changed in the gene string.

  • For example, “AACCGGTT” –> “AACCGGTA” is one mutation.

There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string.

Given the two gene strings startGene and endGene and the gene bank bank, return the minimum number of mutations needed to mutate from startGene to endGene. If there is no such a mutation, return -1.

Note that the starting point is assumed to be valid, so it might not be included in the bank.

Example 1:
Input: startGene = “AACCGGTT”, endGene = “AACCGGTA”, bank = [“AACCGGTA”]
Output: 1

Example 2:
Input: startGene = “AACCGGTT”, endGene = “AAACGGTA”, bank = [“AACCGGTA”,”AACCGCTA”,”AAACGGTA”]
Output: 2

2. Coding Pattern Used in Solution

The coding pattern used in this code is Graph Breadth-First Search (BFS). The problem involves finding the shortest path (minimum mutations) from the startGene to the endGene in a graph where each gene is a node, and edges exist between nodes that differ by exactly one character. BFS is the ideal approach for solving shortest path problems in an unweighted graph.

3. Code Implementation in Different Languages

3.1 Minimum Genetic Mutation C++

class Solution {
public:
    int minMutation(string startGene, string endGene, vector<string>& bank) {
        queue<string> q;
        unordered_map<string, int> vis;
        int steps = 0;
        q.push(startGene);
        vis[startGene] = 1;
        while (!q.empty()) {
            for (int i = q.size(); i > 0; i--) {
                string s = q.front();
                q.pop();
                if (s == endGene) return steps;
                for (int j = 0; j < 8; j++) {
                    char oc = s[j];
                    for (int k = 0; k < 4; k++) {
                        s[j] = "ACGT"[k];
                        if (!vis[s] && find(bank.begin(), bank.end(), s) != bank.end()) {
                            q.push(s);
                            vis[s] = 1;
                        }
                    }
                    s[j] = oc;
                }
            }
            steps += 1;
        }
        return -1;
    }
};

3.2 Minimum Genetic Mutation Java

class Solution {
    public int minMutation(String startGene, String endGene, String[] bank) {
        Queue<String> q = new LinkedList<>();
        HashSet<String> vis = new HashSet<String>();
        List<String> banks = Arrays.asList(bank);
        int steps = 0;
        q.add(startGene);
        vis.add(startGene);
        while (!q.isEmpty()) {
            for (int i = q.size(); i > 0; i--) {
                String s = q.poll();
                if (s.equals(endGene)) return steps;
                char[] ca = s.toCharArray();
                for (int j = 0; j < 8; j++) {
                    char oc = ca[j];
                    for (int k = 0; k < 4; k++) {
                        ca[j] = "ACGT".charAt(k);
                        String t = new String(ca);
                        if (!vis.contains(t) && banks.contains(t)) {
                            q.add(t);
                            vis.add(t);
                        }
                    }
                    ca[j] = oc;
                }
            }
            steps += 1;
        }
        return -1;
    }
}

3.3 Minimum Genetic Mutation JavaScript

var minMutation = function(startGene, endGene, bank) {
	const choices = ['A', 'C', 'G', 'T'];
	const queue = [startGene];
	const seen = new Set([startGene]);
	let steps = 0;
	while (queue.length !== 0) {
		const nodesInQueue = queue.length;
		for (let j = 0; j < nodesInQueue; j++) {
			const node = queue.shift();
			if (node === endGene)
				return steps;
			for (const choice of choices) {
				for (let i = 0; i < node.length; i++) {
					const neighbor = node.substring(0, i) + choice + node.substring(i + 1);
					if (!seen.has(neighbor) && bank.includes(neighbor)) {
						queue.push(neighbor);
						seen.add(neighbor);
					}
				}
			}
		}
		steps++;
	}
	return -1;
}

3.4 Minimum Genetic Mutation Python

class Solution(object):
    def minMutation(self, startGene, endGene, bank):
        queue, seen = deque([(startGene, 0)]), {startGene}
        while queue:
            s, n = queue.popleft()
            if s == endGene: return n
            for i in range(8):
                for ch in 'ACGT':                         
                    m = s[:i]+ch+s[i+1:]
                    if m in bank and m not in seen:
                        seen.add(m)
                        queue.append((m, n+1))
        return -1

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(N * M²)O(N + M)
JavaO(N * M²)O(N + M)
JavaScriptO(N * M²)O(N + M)
PythonO(N * M²)O(N + M)

here,
– N: Number of genes in the bank.
– M: Length of each gene.

Scroll to Top