Abhishek-Chaudhary-InfoCepts
11/18/2018 - 6:29 AM

MinimumMutationGene.java

package com.abhishek.dojo;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;

public class MinimumMutationGene {
	
	public static void main(String[] args) {
		minMutation("AACCGGTT", "AAACGGTA", new String[] {"AACCGGTA", "AACCGCTA", "AAACGGTA"});
	}
	
    public static int minMutation(String start, String end, String[] bank) {
        if (start==null || end==null || start.length()!=end.length()) return -1;
        int steps = 0;
        char[] mutations = new char[]{'A', 'C', 'G', 'T'};
        HashSet<String> validGene = new HashSet<String>();
        for (String str : bank) {
            validGene.add(str);
        }
        if (!validGene.contains(end)) return -1;
        if (validGene.contains(start)) validGene.remove(start);
        Queue<String> q = new LinkedList<String>();
        // add start string to queue
        q.offer(start);
        while (!q.isEmpty()) {
            int size = q.size();
            // iterate entire queue based on it size
            for (int k=0; k<size; k++) {
            	// get from the queue
                String cur = q.poll();
                // iterate over entire string
                for (int i=0; i<cur.length(); i++) {
                	// at every character position, add all possible mutations
                	// if a mutation matches with end, return steps + 1
                	// if bank contains mutation, remove it from bank and treat the target string as source mutation
                    for (char c : mutations) {
                        StringBuilder ss = new StringBuilder(cur);
                        ss.setCharAt(i, c);
                        String afterMutation = ss.toString();
                        if (afterMutation.equals(end)) return steps+1;
                        if (validGene.contains(afterMutation)) {
                            validGene.remove(afterMutation);
                            // add to the queue
                            q.offer(afterMutation);
                        }
                    }
                }
            }
            steps++;
        }
        return -1;
    }


}