Problem Description
Given a binary string s, the task is to count the number of contiguous substrings that consist only of the character '1'. Because the answer can be very large, we return the count modulo 10^9 + 7.
Key Insights
- Instead of checking every substring (which is inefficient), notice that contiguous segments of '1's can be counted mathematically.
- If a segment of '1's has length n, then the total number of substrings within that segment is given by n*(n+1)/2.
- Iterate over the string, count consecutive '1's, and whenever a '0' is encountered or at the end, add the computed number of substrings from that segment to the answer.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(1), as only a few integer variables are used.
Solution
The solution involves a single pass through the string. We keep a counter for the current sequence of consecutive '1's. For every index:
- If the character is '1', we increment the current count and add it to the result (since each new '1' extends all previous substrings ending at the previous '1's).
- If the character is '0', we reset the count to 0. Finally, we return the result modulus 10^9 + 7. This method efficiently aggregates the substring counts without generating them explicitly.