|
| 1 | +# [Problem 1513: Number of Substrings With Only 1s](https://leetcode.com/problems/number-of-substrings-with-only-1s/description/?envType=daily-question) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +Sorry — I can’t share internal stream-of-consciousness. Brief summary instead: scan the string once to find contiguous runs of '1's; each run of length k contributes k*(k+1)/2 substrings made of only '1's. Sum those contributions modulo 10^9+7. |
| 5 | + |
| 6 | +## Refining the problem, round 2 thoughts |
| 7 | +- We need a single pass O(n) algorithm: iterate through s, count current consecutive '1's; when a '0' or end is reached, add k*(k+1)//2 to the result and reset the counter. |
| 8 | +- Use modulo 1_000_000_007 to avoid overflow; apply modulo when adding each run's count. |
| 9 | +- Edge cases: all zeros (answer 0), all ones (single run), alternating characters. |
| 10 | +- Alternative: maintain running contribution incrementally (add current_count when you see a '1'), but both approaches are O(n) time and O(1) space. |
| 11 | +- Time complexity: O(n). Space complexity: O(1). |
| 12 | + |
| 13 | +## Attempted solution(s) |
| 14 | +```python |
| 15 | +class Solution: |
| 16 | + def numSub(self, s: str) -> int: |
| 17 | + MOD = 10**9 + 7 |
| 18 | + res = 0 |
| 19 | + count = 0 # current consecutive '1's |
| 20 | + |
| 21 | + for ch in s: |
| 22 | + if ch == '1': |
| 23 | + count += 1 |
| 24 | + else: |
| 25 | + if count: |
| 26 | + res = (res + count * (count + 1) // 2) % MOD |
| 27 | + count = 0 |
| 28 | + # handle trailing run of '1's |
| 29 | + if count: |
| 30 | + res = (res + count * (count + 1) // 2) % MOD |
| 31 | + |
| 32 | + return res |
| 33 | +``` |
| 34 | +- Notes: |
| 35 | + - Approach: Count contiguous '1' runs. For a run of length k, number of substrings inside it = k*(k+1)/2 (sum of 1..k). |
| 36 | + - Time complexity: O(n), where n = len(s), because we scan the string once. |
| 37 | + - Space complexity: O(1), only a few integer variables used. |
| 38 | + - Implementation detail: use modulo 10^9+7 when adding each run to keep numbers small. |
0 commit comments