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
  • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

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

Updated on: 29-Dec-2020

452 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements