Program to count substrings with all 1s in binary string in Python


Suppose we have a binary string s. We have to find the number of substrings that contain only "1"s. If the answer is too large, mod the result by 10^9+7.

So, if the input is like s = "100111", then the output will be 7, because the substrings containing only "1"s are ["1", "1", "1", "1", "11", "11" and "111"]

To solve this, we will follow these steps −

  • a := 0
  • count := 0
  • for i in range 0 to size of s - 1, do
    • if s[i] is same as "0", then
      • a := 0
    • otherwise,
      • a := a + 1
      • count := count + a
  • return count

Example

Let us see the following implementation to get better understanding −

def solve(s):
   a = 0
   count = 0
   for i in range(len(s)):
      if s[i] == "0":
         a = 0
      else:
         a += 1
         count += a
   return count

s = "100111"
print(solve(s))

Input

"100111"

Output

7

Updated on: 18-Oct-2021

405 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements