

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
- Related Questions & Answers
- Python - List Initialization with alternate 0s and 1s
- Check if a string has m consecutive 1s or 0s in Python
- Check if it is possible to rearrange rectangles in a non-ascending order of breadths in Python
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- Check if it is possible to transform one string to another in Python
- Check if it is possible to create a palindrome string from given N in Python
- Check if it is possible to convert one string into another with given constraints in Python
- Is it possible to check if a String only contains ASCII in java?
- Check if it is possible to create a polygon with a given angle in Python
- Check if it is possible to survive on Island in Python
- Check if it is possible to create a polygon with given n sidess in Python
- Check if all the 1s in a binary string are equidistant or not in Python
- Encoding a number string into a string of 0s and 1s in JavaScript
- XOR counts of 0s and 1s in binary representation in C++
- Check if it is possible to serve customer queue with different notes in Python
Advertisements