DEV Community

Eric See
Eric See

Posted on

Algorithm - How to derive Minimum Swap between 'a' or 'b' to break 3 consecutives same characters

I encounter this in Codility, so going to share my solution.


findSwapCharacterCounts = function (S) {
    console.log(`Processing..`, S);
    var next = 0;
    while(next<S.length-1){
        var char = S[next]
        var next_char = S[next+1];
        if(next_char==char) {
           // console.log(`${char} same as ${next_char}`);
            if ((next_char == S[next+1]) && (next_char === S[next+2])){

                var end_char = S[next+2];
                var swap_char = end_char==="a"?"b":"a";
              //  console.log(`index=${next+2}, swap_char=${swap_char}`);
                var new_str = "";
                for (var j=0; j<S.length;j++){               
                    if (j==next+2){
                        new_str+=swap_char;
                    } else {
                        new_str+=S[j];
                    }
                }
                return findSwapCharacterCounts(new_str)+1;
            }

        } else {
           // console.log(`${char} different ${next_char}`);
        }
        next++;
    }
    return 0;
}

var B_1 = "baaaaa";
var B_2 = "baaaaaa";
var B_3 = "ababababa";
var B_4 = "abbbaaab";
console.log(findSwapCharacterCounts(B_1));
console.log(findSwapCharacterCounts(B_2));
console.log(findSwapCharacterCounts(B_3));
console.log(findSwapCharacterCounts(B_4)); 


Enter fullscreen mode Exit fullscreen mode

Top comments (0)