
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Changes Required for Alternating Binary String in Python
Suppose we have a binary string s. Let us consider an operation where we can flip one bit. The string s is called alternating string if no two adjacent characters are same. We have to find the minimum number of operations needed to make s alternating.
So, if the input is like s = "11100011", then the output will be 3 because if we flip bits at position 1, 4 and 7, then, it will be "10101010", then all are alternating.
To solve this, we will follow these steps −
change := 0
even_1 := 0, even_0 := 0
odd_1 := 0, odd_0 := 0
-
for i in range 0 to size of s - 1, do
-
if i is even, then
-
if s[i] is same as '1', then
even_1 := even_1 + 1
-
otherwise,
even_0 := even_0 + 1
-
-
otherwise,
-
if s[i] is same as '1', then
odd_1 := odd_1 + 1
-
otherwise,
odd_0 := odd_0 + 1
-
-
-
if (even_1+odd_0) > (even_0+odd_1), then
change := even_0 + odd_1
-
otherwise,
change := even_1 + odd_0
return change
Example (Python)
Let us see the following implementation to get better understanding &minnus;
def solve(s): change = 0 even_1 = 0 even_0 = 0 odd_1 = 0 odd_0 = 0 for i in range(len(s)): if(i%2 == 0): if(s[i]=='1'): even_1 +=1 else: even_0 +=1 else: if(s[i] == '1'): odd_1 +=1 else: odd_0 +=1 if((even_1+odd_0)>(even_0+odd_1)): change = even_0 + odd_1 else: change = even_1 + odd_0 return change s = "11100011" print(solve(s))
Input
"11100011"
Output
3