Minimum Number of Flips
Given a binary string (containing only 0s and 1s). We need to make this string a sequence of alternate characters (0 and 1) by flipping some of the bits, our goal is to minimize the number of bits to be flipped. Write a program to determine the minimum number of bits to reach the goal
Examples:
Input:
0000 (binary string)
Output:
2
Input:
110 (binary string)
Output:
1
Example explanations:
Input:
0000
Output strings possible from the input string,
which satisfies the constraints:
0101
1010
Both strings are valid and both require 2 bits to be flipped.
Thus minimum no of flipping needed is 2
Input:
110
Output strings possible from the input string,
which satisfies the constraints:
010
101
The first one needs only one flips
While the second one need two flips
Hence minimum flip required is 1
Algorithm:
1) Declare variables and initialize like below.
flip0 = 0, flip1 = 0, flag0 = 0, flag1 = 1 flip0=number of flips needed when converted string starts with 0 flip1=number of flips needed when converted string starts with 1 flag0=the current character value that should be at current string index, incase converted string starts from 0, value changes from 0 to 1, 1 to 0 alternatively flag1 = the current character value that should be at current string index, incase converted string starts from 1, value changes from 0 to 1, 1 to 0 alternatively2) Count number of flips needed for converting input string to the valid string starting with 0
for i=0:s.length()-1 iF (flag0 != s[i]-'0') flip0++; END IF flag0=1-flag0; END FOR3) Count number of flips needed for converting input string to the valid string starting with 1
for i=0:s.length()-1 iF (flag1 != s[i]-'0') flip1++; END IF flag1=1-flag1; END FOR4) return minimum of flip0 and flip1;
C++ implementation
Output
need an explanation for this answer? contact us directly to get an explanation for this answer