Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python


Suppose we have a binary string s whose length is 2 or more. We have to check whether we can rearrange s such that there are alternate 0s and 1s.

So, if the input is like s = "1000111", then the output will be True as we can form "1010101" from s.

To solve this, we will follow these steps −

  • one_count := count of 1 in binary string s
  • zero_count := count of 0 in binary string s
  • if size of s is even, then
    • return true when one_count is same as zero_count otherwise false
  • return true when |one_count - zero_count| is same as 1 otherwise false

Example

Let us see the following implementation to get better understanding −

 Live Demo

def solve(s):
   one_count = s.count('1')
   zero_count = s.count('0')
   if len(s) % 2 == 0 :
      return (one_count == zero_count)
   return abs(one_count - zero_count) == 1
s = "1000111"
print(solve(s))

Input

"1000111"

Output

True

Updated on: 18-Jan-2021

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements