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
Program to check if binary string has at most one segment of ones or not using Python
Binary strings often need validation to check specific patterns. A common requirement is to verify if a binary string has at most one contiguous segment of ones. This means all the '1's should be grouped together without any '0's in between.
For example, "111000" has one segment of ones, while "11010" has two separate segments.
Problem Understanding
Given a binary string without leading zeros, we need to determine if it contains at most one contiguous segment of ones. The string should have all '1's grouped together, followed by all '0's (if any).
Examples
"111000" ? True (one segment: "111")
"1" ? True (single character)
"0" ? True (no ones)
"11010" ? False (two segments: "11" and "1")
Solution Approach
We can solve this by tracking when we encounter zeros. Once we find a '0', any subsequent '1' indicates a second segment ?
def solve(s):
count = -1
if len(s) == 1:
return True
for i in s:
if i == "1" and count > -1:
return False
elif i == "0":
count += 1
return True
# Test with different examples
test_cases = ["11100", "1", "0", "11010", "111", "101"]
for s in test_cases:
result = solve(s)
print(f"'{s}' ? {result}")
'11100' ? True '1' ? True '0' ? True '11010' ? False '111' ? True '101' ? False
How It Works
Initialize counter: Set count = -1 to track zero encounters
Handle edge case: Single character strings always return True
-
Iterate through string: For each character:
If we find '1' after encountering zeros (count > -1), return False
If we find '0', increment the counter
Return True: If no violations found, the string is valid
Alternative Solution
A simpler approach using Python string methods ?
def check_one_segment(s):
# Find the first occurrence of '0'
try:
zero_index = s.index('0')
# Check if there are any '1's after the first '0'
return '1' not in s[zero_index:]
except ValueError:
# No '0' found, so all are '1's
return True
# Test the alternative solution
test_cases = ["11100", "1", "0", "11010", "111", "101"]
for s in test_cases:
result = check_one_segment(s)
print(f"'{s}' ? {result}")
'11100' ? True '1' ? True '0' ? True '11010' ? False '111' ? True '101' ? False
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Counter Approach | O(n) | O(1) | Moderate |
| String Methods | O(n) | O(1) | High |
Conclusion
Both approaches efficiently check for at most one contiguous segment of ones. The counter method tracks zero encounters, while the string method finds the first zero and checks for subsequent ones. Choose based on readability preference and coding style.
