Given a binary string s
without leading zeros, return true
if s
contains at most one contiguous segment of ones. Otherwise, return false
.
Example 1:
Input: s = "1001" Output: false Explanation: The ones do not form a contiguous segment.
Example 2:
Input: s = "110" Output: true
Constraints:
1 <= s.length <= 100
s[i]
is either '0'
or '1'
.s[0]
is '1'
.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force method for this problem is straightforward: examine the entire string of zeroes and ones character by character. The goal is to identify if there is a single, unbroken sequence of ones, possibly surrounded by zeroes.
Here's how the algorithm would work step-by-step:
def check_if_binary_string_has_at_most_one_segment_of_ones(binary_string):
number_of_characters = len(binary_string)
index = 0
# Iterate to find the end of the first segment of ones.
while index < number_of_characters and binary_string[index] == '1':
index += 1
# If the whole string is ones, return True.
if index == number_of_characters:
return True
# Skip all the zeros.
while index < number_of_characters and binary_string[index] == '0':
index += 1
# Check if there are any more ones after the zeros.
# If we find any ones after zeros, it's not a single segment.
if index < number_of_characters:
return False
return True
The problem asks us to check if a string of ones and zeros has at most one continuous block of ones. The efficient way is to scan the string and look for a specific pattern: a zero followed by a one.
Here's how the algorithm would work step-by-step:
def check_if_binary_string_has_at_most_one_segment_of_ones(binary_string):
found_zero = False
for i in range(len(binary_string)):
if binary_string[i] == '0':
# Record the first occurence of zero.
found_zero = True
if found_zero:
# After the first zero, look for ones.
if binary_string[i] == '1':
# If we find a one, it's not one segment.
return False
return True
Case | How to Handle |
---|---|
Empty string | Return true, as an empty string has zero segments of ones, which is at most one. |
String with only '0's | Return true, as there are no segments of ones, which is at most one. |
String with only '1's | Return true, as the entire string is a single segment of ones. |
String starts and ends with '1's, with '0's in between | Return true, as it's a single contiguous segment of ones. |
String contains multiple segments of '1's separated by '0's | Return false, as it violates the 'at most one segment' condition. |
String with a single '1' at the beginning | Return true if the rest are zeros. |
String with a single '1' at the end | Return true if the front are zeros. |
String with '0's followed by '1's followed by '0's | Return true, as there is only one segment of ones. |