Identifying patterns in binary strings is a common problem in competitive programming and technical interviews. In this article, we will discuss how to find all occurrences of the pattern 0(1+)0 in a given binary string, where:
This problem can be solved efficiently by scanning the string and counting the occurrences of this pattern.
Input:
01101111010
Output:
3
Explanation:
The given binary string: 01101111010
01101111010
→ count = 101101111010
→ count = 201101111010
→ count = 3So, the total number of patterns 0(1+)0 in this string is 3.
binary_str = "01101111010"
Index | Character | Action Taken |
---|---|---|
0 | 0 | Start of potential pattern |
1 | 1 | Valid (we need at least one ‘1’) |
2 | 1 | Still valid |
3 | 0 | Found Pattern 1 (0110) |
4 | 1 | Start of another pattern |
5 | 1 | Still valid |
6 | 1 | Still valid |
7 | 1 | Still valid |
8 | 0 | Found Pattern 2 (011110) |
9 | 1 | Start of another pattern |
10 | 0 | Found Pattern 3 (010) |
Total 0(1+)0 patterns found = 3
3
binary_str = "01010"
Index | Character | Action Taken |
---|---|---|
0 | 0 | Start of potential pattern |
1 | 1 | Valid (we need at least one ‘1’) |
2 | 0 | Found Pattern 1 (010) |
3 | 1 | Start of another pattern |
4 | 0 | Found Pattern 2 (010) |
Total 0(1+)0 patterns found = 2
2
binary_str = "0000"
0
binary_str = "011110"
1
To find and count the required patterns in the given binary string, follow these steps:
def count_patterns(binary_str):
count = 0
i = 0
while i < len(binary_str) - 1:
if binary_str[i] == '0':
j = i + 1
while j < len(binary_str) and binary_str[j] == '1':
j += 1
if j < len(binary_str) and binary_str[j] == '0':
count += 1
i = j
i += 1
return count
# Example usage
binary_str = input("Enter the binary string: ")
print("Total 0(1+)0 patterns:", count_patterns(binary_str))
To better understand how the program works, consider the following flow diagram:
Input: 01101111010
Index: 01234567890
------------------
0 → 1 → 1 → 0 → Found (1st pattern)
0 → 1 → 1 → 1 → 1 → 0 → Found (2nd pattern)
0 → 1 → 0 → Found (3rd pattern)
Total patterns found: 3
Finding patterns in binary strings is a crucial skill for technical interviews and problem-solving challenges. The 0(1+)0 pattern can be efficiently identified using a linear scan approach with an O(n) complexity. By implementing the given algorithm, you can quickly determine the number of occurrences in any binary string.