Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
Given a binary string, we need to check if we can rearrange it to have alternating 0s and 1s. For this to be possible, the counts of 0s and 1s must differ by at most 1.
For example, with input s = "1000111", the output will be True because we can form "1010101" from the given string.
Algorithm
To solve this problem, we follow these steps:
- Count the number of 1s and 0s in the binary string
- If the string length is even, both counts must be equal
- If the string length is odd, the counts must differ by exactly 1
Example
Let us see the implementation to better understand the approach:
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
# Test the function
s = "1000111"
print(f"Input: {s}")
print(f"Output: {solve(s)}")
Input: 1000111 Output: True
How It Works
The string "1000111" has 4 ones and 3 zeros. Since the length is 7 (odd), we need the counts to differ by exactly 1, which they do (|4-3| = 1). Therefore, we can arrange it as "1010101".
Additional Examples
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
# Test with multiple examples
test_cases = ["1010", "1100", "111000", "10101"]
for test in test_cases:
result = solve(test)
print(f"'{test}' -> {result}")
'1010' -> True '1100' -> True '111000' -> True '10101' -> True
Conclusion
To check if a binary string can be rearranged with alternating 0s and 1s, count the occurrences of each digit. For even-length strings, counts must be equal; for odd-length strings, they must differ by exactly 1.
