Use BFS starting from startGene. Mutate single characters to valid bank genes, tracking shortest mutation sequence distance.
def minMutation(startGene, endGene, bank):
bankSet = set(bank)
if endGene not in bankSet:
return -1
queue = [(startGene, 0)]
visited = {startGene}
while queue:
current, dist = queue.pop(0)
if current == endGene:
return dist
for i in range(8):
for char in "ACGT":
mutation = current[:i] + char + current[i+1:]
if mutation in bankSet and mutation not in visited:
visited.add(mutation)
queue.append((mutation, dist + 1))
return -1
class Solution {
public int minMutation(String startGene, String endGene, String[] bank) {
Set bankSet = new HashSet<>(Arrays.asList(bank));
if (!bankSet.contains(endGene)) return -1;
Queue> queue = new LinkedList<>();
queue.add(new Pair<>(startGene, 0));
Set visited = new HashSet<>();
visited.add(startGene);
char[] chars = {'A', 'C', 'G', 'T'};
while (!queue.isEmpty()) {
Pair currentPair = queue.poll();
String current = currentPair.getKey();
int dist = currentPair.getValue();
if (current.equals(endGene)) return dist;
for (int i = 0; i < 8; i++) {
for (char c : chars) {
char[] mutationArr = current.toCharArray();
mutationArr[i] = c;
String mutation = new String(mutationArr);
if (bankSet.contains(mutation) && !visited.contains(mutation)) {
visited.add(mutation);
queue.add(new Pair<>(mutation, dist + 1));
}
}
}
}
return -1;
}
}