- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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.

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 - 2, 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

Let us see the following implementation to get better understanding −

## Example

def solve(s, m): str_size = len(s) count_0 = 0 count_1 = 0 for i in range(0, str_size - 1): 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))

## Input

"1110111000111", 3

## Output

True

- Related Articles
- Check if a binary string has a 0 between 1s or not in C++
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- Check if all the 1s in a binary string are equidistant or not in Python
- Encoding a number string into a string of 0s and 1s in JavaScript
- Print n 0s and m 1s such that no two 0s and no three 1s are together in C Program
- How do I check if a string has alphabets or numbers in Python?
- Check if a binary string contains consecutive same or not in C++
- Check if a binary string has two consecutive occurrences of one everywhere in C++
- Python - List Initialization with alternate 0s and 1s
- Constructing a string of alternating 1s and 0s of desired length using JavaScript
- Check whether a number has consecutive 0’s in the given base or not using Python
- Check if a string is Isogram or not in Python
- Python - Check if a given string is binary string or not
- Check if the String has only unicode digits or space in Java

Advertisements