-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0433-minimum-genetic-mutation.js
More file actions
47 lines (39 loc) · 1.43 KB
/
0433-minimum-genetic-mutation.js
File metadata and controls
47 lines (39 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Minimum Genetic Mutation
* Time Complexity: O(N * L^2).
* Space Complexity: O(N * L)
*/
var minMutation = function (startGene, endGene, bank) {
const geneBankSet = new Set(bank);
if (!geneBankSet.has(endGene)) {
return -1;
}
const bfsPathQueue = [[startGene, 0]];
const visitedGenesSet = new Set();
visitedGenesSet.add(startGene);
const geneLengthValue = 8;
const possibleNucleotides = ['A', 'C', 'G', 'T'];
while (bfsPathQueue.length > 0) {
const currentEntry = bfsPathQueue.shift();
const currentGeneSequence = currentEntry[0];
const currentStepCount = currentEntry[1];
if (currentGeneSequence === endGene) {
return currentStepCount;
}
for (let mutationPosition = 0; mutationPosition < geneLengthValue; mutationPosition++) {
for (const nucleotideOption of possibleNucleotides) {
if (nucleotideOption === currentGeneSequence[mutationPosition]) {
continue;
}
const leftSegment = currentGeneSequence.slice(0, mutationPosition);
const rightSegment = currentGeneSequence.slice(mutationPosition + 1);
const mutatedCandidateGene = leftSegment + nucleotideOption + rightSegment;
if (geneBankSet.has(mutatedCandidateGene) && !visitedGenesSet.has(mutatedCandidateGene)) {
visitedGenesSet.add(mutatedCandidateGene);
bfsPathQueue.push([mutatedCandidateGene, currentStepCount + 1]);
}
}
}
}
return -1;
};