JavaScript Program to FindNumber of Flips to make Binary String Alternate
Last Updated :
29 Aug, 2024
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 to invert a character
function invertCharacter(ch) {
return ch === '0' ? '1' : '0';
}
/* Function to compute the minimum flips when
forming an alternating string with
the given starting character
*/
function calculateMinimumFlipsStartingFrom(str, startingChar) {
let flipCount = 0;
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) !== startingChar)
{
flipCount++;
}
// Toggle the expected character in each iteration
startingChar =
invertCharacter(startingChar);
}
return flipCount;
}
/* Function to determine the minimum
number of flips required to make a binary
*/
function findMinimumFlipsForStringAlternation(str) {
return Math
.min(calculateMinimumFlipsStartingFrom(str, '0'),
calculateMinimumFlipsStartingFrom(str, '1'));
}
// Driver code to test the above method
let binaryStr = "111000111";
console.log(
findMinimumFlipsForStringAlternation(binaryStr));
Time Complexity: O(N)
Auxiliary Space: O(1)
Using a single iteration
This approach iterates through the binary string and calculates the flip count required for two scenarios: one where the string starts with '0' and the other where it starts with '1'. For each character position, it checks whether the expected character ('0' for even positions and '1' for odd positions) matches the actual character. If not, it increments the corresponding flip count. Finally, it returns the minimum of the two flip counts as the result.
JavaScript
function findMinimumFlipsForStringAlternation(str) {
let flipCountStartWith0 = 0;
let flipCountStartWith1 = 0;
// Iterate through the string
for (let i = 0; i < str.length; i++) {
// If index is even, expected character should be '0'
if (i % 2 === 0) {
if (str[i] !== '0') {
flipCountStartWith0++;
}
if (str[i] !== '1') {
flipCountStartWith1++;
}
}
else {
if (str[i] !== '1') {
flipCountStartWith0++;
}
if (str[i] !== '0') {
flipCountStartWith1++;
}
}
}
// Return the minimum of the two flip counts
return Math.min(flipCountStartWith0, flipCountStartWith1);
}
let binaryStr = "111000111";
console.log(findMinimumFlipsForStringAlternation(binaryStr)); // Output: 3
Approach: Bitwise Pattern Matching
Idea: Utilize bitwise operations to compute the number of flips needed to match both possible alternating patterns. This approach is a variation of the initial method but focuses on utilizing bit manipulation to streamline the solution.
Steps:
- Generate Two Patterns: We generate two possible alternating patterns for comparison:
- Pattern 1 starts with '0':
"010101..."
(repeating) - Pattern 2 starts with '1':
"101010..."
(repeating)
- Count Flips for Both Patterns: Compare the input string against both patterns and count the number of mismatches (flips) required for each pattern.
- Return Minimum Flips: The result is the minimum number of flips required between the two patterns.
Example:
JavaScript
function countFlipsToMatchPattern(str, pattern) {
let flipCount = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] !== pattern[i]) {
flipCount++;
}
}
return flipCount;
}
function findMinimumFlipsForStringAlternation(str) {
let n = str.length;
let pattern1 = '';
let pattern2 = '';
for (let i = 0; i < n; i++) {
pattern1 += i % 2 === 0 ? '0' : '1';
pattern2 += i % 2 === 0 ? '1' : '0';
}
let flipsForPattern1 = countFlipsToMatchPattern(str, pattern1);
let flipsForPattern2 = countFlipsToMatchPattern(str, pattern2);
return Math.min(flipsForPattern1, flipsForPattern2);
}
let binaryStr = "111000111";
console.log(findMinimumFlipsForStringAlternation(binaryStr));
Similar Reads
JavaScript Program for Min flips of continuous characters to make all characters same in a String In this article, we will learn about Min flips of continuous characters to make all characters the same in a string using JavaScript. Min flips of continuous characters in a string refer to the minimum number of changes required to turn a sequence of adjacent characters into a uniform sequence, ensu
3 min read
JavaScript Program to Check if all Bits can be made Same by Single Flip In this article, we will explore how to determine if it's possible to make all bits the same in a binary string by performing a single flip operation. We will cover various approaches to implement this in JavaScript and provide code examples for each approach.Examples:Input: 1101Output: YesExplanati
5 min read
JavaScript Program to Check if a Number has Bits in an Alternate Pattern JavaScript can be used to assess whether a given number follows an alternating pattern in its binary representation. By examining the binary digits of the number, one can determine if the sequence alternates between 0s and 1s, aiding in understanding the binary structure of the input. Examples: Inpu
2 min read
Java Program to Convert Octal to Binary Given an Octal number as input, the task is to convert that number into its Binary equivalent number. Example: Input: Octal Number = 513 Output: Binary equivalent value is: 101001011 Explanation : Binary equivalent value of 5: 101 Binary equivalent value of 1: 001 Binary equivalent value of 3: 011Oc
5 min read
Java Program to Convert a Decimal Number to Binary Number using Arrays as Stacks Given an Integer number convert into Binary Number using arrays as a stack. Example: Input : 10 Output: 1010 Input : 16 Output: 10000 Approach: Divide the number by 2 and store the remainder of the number in the array.Divide the number by 2.Repeat the process until the number becomes zero.Print the
1 min read
Java Program to Swap Corner Words and Reverse Middle Characters of a String Given a string containing n numbers of words. The task is to swap the corner words of the string and reverses all the middle characters of the string. Input: "Hello this is the GFG user" Output: "user GFG eth si siht Hello" Input: "Hello Bye" Output: "Bye Hello" Methods: Using the concept of ASCII v
5 min read
Count Number of Distinct Binary Strings After Applying Flip Operations Given a binary string s and a positive integer k. In a operation you can repeatedly choose any substring of length k in s and flip all its characters (0s to 1s, 1s to 0s). The task is to return the number of distinct strings that can be obtained, modulo 10^9 + 7. You can perform the flip operation a
5 min read
Rearrange a Binary String with Alternating 0s and 1s in Python We are given a binary string and we have to check whether it is possible to rearrange the string with alternate 0s and 1s. Below are a few examples to understand the problem statement clearly. Examples:Input: "1011"Output: FalseExplanation: We canât rearrange the string such that it has alternate 0s
2 min read
Javascript Program for Longest subsequence of a number having same left and right rotation Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation. Examples: Input: S = "100210601" Output: 4 Explanation: The subsequence "0000" satisfies the necessary condition. The subsequence "1010" generates the string "0101"
4 min read
Position of leftmost set bit in given binary string where all 1s appear at end Given a binary string S of length N, such that all 1s appear on the right. The task is to return the index of the first set bit found from the left side else return -1. Examples: Input: s = 00011, N = 5Output: 3Explanation: The first set bit from the left side is at index 3. Input: s = 0000, N = 4Ou
5 min read