You are given a binary string ‘STR’, containing only zeroes and ones. This string does not contain any leading zero.
Your task is to determine if this string contains at most one contiguous segment of ones.
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the T test cases follow.
The first line of each test case contains the binary string ‘STR’.
Output Format:
For each test case, print “Yes” if the string contains at most one contiguous segment of ones or print “No” if it contains more than one contiguous segment.
Output for each test case will be printed in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= |STR| < 10^6
Where ‘T’ denotes the number of test cases and |STR| represents the length of the string ‘STR’
Time Limit: 1sec
1
11100
Yes
In this test case, we can observe that the string contains only one contiguous segment of ones. This segment starts at the 0th index and ends at the 2nd index.
1
111011
No
In this case, the string contains two contiguous segments of ones. The first segment starts at the 0th index and ends at the 2nd index. The second segment starts at the 4th index and ends at the 5th index.
Think about how do we know when a new segment starts
We know that the given string does not contain leading zeroes. This means that the string definitely has at least one segment of ones. For this string to contain only one segment of ones, this should be the only segment. When the first zero appears, this segment ends at that index. So, if any zero is followed by a one, then that will be the new segment. So the approach is to find whether the string contains a zero which is followed by a one or not. If it does contain such a zero, then the string has more than one segment of ones.
Algorithm:
O(N), where N is the length of the binary string.
We are going through the entire string and checking each character only once. This takes linear time.
O(1)
We are not using any extra space.