The Number of Substrings With Only 1s problem gives you a binary string and asks you to count all substrings that consist entirely of '1's. This is equivalent to finding all runs of consecutive '1's and summing the triangular numbers for each run. This coding problem tests the "count substrings in a run" mathematical insight.
Google asks this medium problem to test whether candidates recognize the incremental run-length counting pattern. For a run of L consecutive '1's, the number of all-1 substrings is L*(L+1)/2. The math and string interview pattern is applied with the same incremental contribution technique used in "smooth descent periods."
Run tracking with incremental count. For each position i, track the length of the current all-1 run ending at i. If s[i]='1', run = prev_run + 1. If s[i]='0', run = 0. Add run to the total count. This incrementally counts all-1 substrings ending at position i as run (since any starting point within the current run forms a valid substring). Apply mod 10^9+7.
s = "0111". Process:
The incremental run count approach — add current run length to total at each step — is cleaner than finding all runs and computing formulas. It's a universal pattern for "count subarrays/substrings of a contiguous type" problems. Practice similar problems: "count subarrays with all equal elements," "number of arithmetic subarray runs." The incremental addition naturally computes L*(L+1)/2 for a run of length L.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count Number of Homogenous Substrings | Medium | Solve | |
| Convert Date to Binary | Easy | Solve | |
| Number of Distinct Binary Strings After Applying Operations | Medium | Solve | |
| Number of Ways to Split a String | Medium | Solve | |
| The Number of Full Rounds You Have Played | Medium | Solve |