Number of Substrings With Only 1s - Problem
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 109 + 7.
Example: For string "111", the substrings are: "1" (3 times), "11" (2 times), "111" (1 time), totaling 6 substrings.
Input & Output
Example 1 — Basic Consecutive 1's
$
Input:
s = "111"
›
Output:
6
💡 Note:
Substrings with only 1's: "1" (at positions 0,1,2), "11" (at positions 0-1,1-2), "111" (at position 0-2). Total: 3+2+1 = 6
Example 2 — Mixed String
$
Input:
s = "0"
›
Output:
0
💡 Note:
No substrings contain only 1's, so the count is 0
Example 3 — Multiple Segments
$
Input:
s = "1101"
›
Output:
3
💡 Note:
Segment "11" contributes 2*(2+1)/2 = 3 substrings, segment "1" contributes 1*(1+1)/2 = 1. But wait, let me recalculate: "1" (pos 0), "11" (pos 0-1), "1" (pos 3). Total = 3
Constraints
- 1 ≤ s.length ≤ 105
- s[i] is either '0' or '1'
Visualization
Tap to expand
Understanding the Visualization
1
Input
Binary string with 1's and 0's
2
Process
Find consecutive segments of 1's
3
Output
Total count of valid substrings
Key Takeaway
🎯 Key Insight: For n consecutive 1's, there are exactly n×(n+1)/2 valid substrings - use this mathematical property instead of checking every substring individually
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code