|
| 1 | +// https://leetcode.com/problems/minimum-genetic-mutation |
| 2 | +// T: O(B) |
| 3 | +// S: O(1) |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.Collections; |
| 7 | +import java.util.HashMap; |
| 8 | +import java.util.HashSet; |
| 9 | +import java.util.LinkedList; |
| 10 | +import java.util.List; |
| 11 | +import java.util.Map; |
| 12 | +import java.util.Queue; |
| 13 | +import java.util.Set; |
| 14 | + |
| 15 | +public class MinimumGeneticMutation { |
| 16 | + private record Info(String mutation, int steps) {} |
| 17 | + |
| 18 | + private static final char[] GENES = new char[] {'A', 'G', 'C', 'T'}; |
| 19 | + |
| 20 | + // n = length of string (8), m = possible number of characters |
| 21 | + // BFS, T: O(V + E) = O(nB + n^m * mn) S: O(n^m) |
| 22 | + public static int minMutation(String startGene, String endGene, String[] bank) { |
| 23 | + final Set<String> genePool = toSet(bank); |
| 24 | + if (!genePool.contains(endGene)) { |
| 25 | + return -1; |
| 26 | + } |
| 27 | + |
| 28 | + final Queue<Info> queue = new LinkedList<>() {{ add(new Info(startGene, 0)); }}; |
| 29 | + final Map<String, Integer> distances = new HashMap<>(); |
| 30 | + |
| 31 | + while (!queue.isEmpty()) { |
| 32 | + final Info info = queue.poll(); |
| 33 | + if (distances.getOrDefault(info.mutation, Integer.MAX_VALUE) <= info.steps) { |
| 34 | + continue; |
| 35 | + } |
| 36 | + distances.put(info.mutation, info.steps); |
| 37 | + |
| 38 | + for (String neighbour : validMutations(genePool, info.mutation)) { |
| 39 | + queue.add(new Info(neighbour, info.steps + 1)); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return distances.getOrDefault(endGene, -1); |
| 44 | + } |
| 45 | + |
| 46 | + // T: O(|s|), S: O(|s|) |
| 47 | + private static List<String> validMutations(Set<String> genePool, String s) { |
| 48 | + final List<String> result = new ArrayList<>(); |
| 49 | + for (int i = 0 ; i < s.length() ; i++) { |
| 50 | + for (char c : GENES) { |
| 51 | + final String mutation = s.substring(0, i) + c + s.substring(i + 1); |
| 52 | + if (genePool.contains(mutation)) { |
| 53 | + result.add(mutation); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + return result; |
| 58 | + } |
| 59 | + |
| 60 | + // T: O(nB) S: O(nB) |
| 61 | + private static Set<String> toSet(String[] bank) { |
| 62 | + final Set<String> set = new HashSet<>(); |
| 63 | + Collections.addAll(set, bank); |
| 64 | + return set; |
| 65 | + } |
| 66 | +} |
0 commit comments