DEV Community

Eric See
Eric See

Posted on

2 1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

nextjs tutorial video

📺 Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay