- Related Questions & Answers
- Check if a binary string has a 0 between 1s or not in C++
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- 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 all the 1s in a binary string are equidistant or not in Python
- Check if a binary string has two consecutive occurrences of one everywhere in C++
- Check if a binary string contains consecutive same or not in C++
- Python - List Initialization with alternate 0s and 1s
- Check if a string has white space in JavaScript?
- Check if the String has only unicode digits or space in Java
- Check if a string is Isogram or not in Python
- Python - Check if a given string is binary string or not
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Minimum toggles to partition a binary array so that it has first 0s then 1s in C++

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

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 −

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))

"1110111000111", 3

True

Advertisements