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 a string has m consecutive 1s or 0s in Python
Suppose we have a binary string s and another value m, we have to check whether the string has m consecutive 1's or m consecutive 0's.
So, if the input is like s = "1110111000111", m = 3, then the output will be True as there are three consecutive 0s and 1s.
Algorithm
To solve this, we will follow these steps ?
- str_size := size of s
- count_0 := 0, count_1 := 0
- for i in range 0 to str_size − 1, do
- if s[i] is same as '0', then
- count_1 := 0
- count_0 := count_0 + 1
- otherwise,
- count_0 := 0
- count_1 := count_1 + 1
- if count_0 is same as m or count_1 is same as m, then
- return True
- if s[i] is same as '0', then
- return False
Example
Let us see the following implementation to get better understanding ?
def solve(s, m):
str_size = len(s)
count_0 = 0
count_1 = 0
for i in range(0, str_size):
if (s[i] == '0'):
count_1 = 0
count_0 += 1
else:
count_0 = 0
count_1 += 1
if (count_0 == m or count_1 == m):
return True
return False
s = "1110111000111"
m = 3
print(solve(s, m))
The output of the above code is ?
True
Using Regular Expressions
We can also solve this problem using regular expressions to find patterns of consecutive characters ?
import re
def solve_regex(s, m):
pattern_0 = '0' * m
pattern_1 = '1' * m
return pattern_0 in s or pattern_1 in s
s = "1110111000111"
m = 3
print(solve_regex(s, m))
The output of the above code is ?
True
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Counter approach | O(n) | O(1) | Single pass scanning |
| String matching | O(n) | O(m) | Simple and readable |
Conclusion
Both approaches effectively check for m consecutive 0s or 1s in a binary string. The counter approach is more memory-efficient, while the string matching approach using the in operator is more readable and concise.
