JavaScript Program to FindNumber of Flips to make Binary String Alternate
Last Updated :
31 Oct, 2023
In this problem, we aim to determine the minimum number of flips needed to transform a binary string into an alternating sequence of ‘0’s and ‘1’s. A flip refers to changing a ‘0’ to ‘1’ or a ‘1’ to ‘0’. The objective is to find the most efficient way to achieve this alternating pattern.
Examples:
Input : binaryStr = “101”
Output : 0
Minimum number of flips required = 0
We cannot flip
Input : binaryStr = “111000111”
Output : 3
Minimum number of flips required = 3
Approach:
We can approach this problem by exploring all potential outcomes. Since we aim to achieve an alternating string, there are only two possibilities:
- One where the alternate string starts with ‘0’ and the other with ‘1’. We’ll examine both scenarios and select the one that demands the fewest flips as our ultimate solution. To assess a scenario, it necessitates O(n) time, during which we’ll traverse through all the characters in the given string.
- If the current character aligns with the expected character for alternation, no action is taken; otherwise, we increment the flip count by 1. Following the examination of strings commencing with ‘0’ and those beginning with ‘1’, we will opt for the string with the minimal flip count.
Syntax:
function calculateMinimumFlips(str,startingChar) {
// Implementation
return flipCount;
}
Example: Below is the implementation of the above approach
Javascript
function invertCharacter(ch) {
return ch === '0' ? '1' : '0' ;
}
function calculateMinimumFlipsStartingFrom(str, startingChar) {
let flipCount = 0;
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) !== startingChar)
{
flipCount++;
}
startingChar =
invertCharacter(startingChar);
}
return flipCount;
}
function findMinimumFlipsForStringAlternation(str) {
return Math
.min(calculateMinimumFlipsStartingFrom(str, '0' ),
calculateMinimumFlipsStartingFrom(str, '1' ));
}
let binaryStr = "111000111" ;
console.log(
findMinimumFlipsForStringAlternation(binaryStr));
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...