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
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"].
Algorithm
To solve this, we will follow these steps −
- Initialize a counter
ato 0 for tracking consecutive 1s - Initialize
countto 0 for total substrings - For each character in the string:
- If character is "0", reset
ato 0 - Otherwise, increment
aand add it tocount
- If character is "0", reset
- Return count
How It Works
When we encounter consecutive 1s, each new 1 can form substrings with all previous 1s in the current sequence. For example, in "111", the first 1 forms 1 substring, the second 1 forms 2 substrings ("1" and "11"), and the third 1 forms 3 substrings ("1", "11", and "111").
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))
The output of the above code is −
7
Step-by-Step Execution
For string "100111", here's how the algorithm works:
| Index | Character | a (consecutive 1s) | count (total substrings) |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
| 1 | 0 | 0 | 1 |
| 2 | 0 | 0 | 1 |
| 3 | 1 | 1 | 2 |
| 4 | 1 | 2 | 4 |
| 5 | 1 | 3 | 7 |
With Modulo Operation
For large inputs, we can add modulo operation as mentioned in the problem statement −
def solve_with_mod(s):
MOD = 10**9 + 7
a = 0
count = 0
for char in s:
if char == "0":
a = 0
else:
a += 1
count = (count + a) % MOD
return count
s = "100111"
print(solve_with_mod(s))
The output remains the same for this small example −
7
Conclusion
This algorithm efficiently counts all-1 substrings by tracking consecutive 1s and adding the count at each position. The time complexity is O(n) and space complexity is O(1), making it optimal for large binary strings.
---