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
Count Substrings With Only 1's: "111" ExampleInput String:111All Valid Substrings:"1" (pos 0)"1" (pos 1)"1" (pos 2)"11" (pos 0-1)"11" (pos 1-2)"111" (pos 0-2)Total Count: 6Formula: 3 × (3+1) ÷ 2 = 6
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
Asked in
Facebook 15 Amazon 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen