Number of Substrings With Only 1s Problem
Description
LeetCode Problem 1513.
Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111"
Output: 9
Explanation: There are 9 substring in total with only 1's characters.
"1" -> 5 times.
"11" -> 3 times.
"111" -> 1 time.
Example 2:
Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.
Example 3:
Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.
Constraints:
1 <= s.length <= 10^5s[i]is either'0'or'1'.
Solution
Approach: Count by the Run Ending at Each Position
Every all-1 substring lies inside one maximal block of consecutive 1s, so the blocks can be counted separately. A block of length k contains k * (k + 1) / 2 substrings.
We do not even need to find the blocks explicitly. Scan the string and keep run, the length of the block of 1s that ends at the current character:
- On a
'1', increaserun. Exactlyrunall-1substrings end at this position (they start at each of the lastruncharacters), so addrunto the answer. - On a
'0', resetrunto0.
Adding 1 + 2 + ... + k over a block gives the same k * (k + 1) / 2. Take the sum modulo 10^9 + 7 as you go: a string of 10^5 ones has about 5 * 10^9 such substrings, which overflows a 32-bit integer.
Complexity: O(n) time and O(1) extra space.
class Solution:
def numSub(self, s: str) -> int:
mod = 10**9 + 7
ans = run = 0 # run: length of the block of 1s ending here
for c in s:
if c == "1":
run += 1
ans = (ans + run) % mod # run new substrings end at this 1
else:
run = 0
return ans