- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements