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: 4
💡 Note: Segment "11" contributes 2*(2+1)/2 = 3 substrings: "1" (pos 0), "1" (pos 1), "11" (pos 0-1). Segment "1" contributes 1*(1+1)/2 = 1 substring: "1" (pos 3). Total = 3 + 1 = 4

Constraints

  • 1 ≤ s.length ≤ 105
  • s[i] is either '0' or '1'

Visualization

Tap to expand
Number of Substrings With Only 1s INPUT Binary String s = "111" 1 idx 0 1 idx 1 1 idx 2 All Substrings of "111": "1" (pos 0) "1" (pos 1) "1" (pos 2) "11" (0-1) "11" (1-2) "111" (0-2) Input String: s = "111" ALGORITHM STEPS 1 Initialize Counter count = 0, consecutive = 0 2 Scan Each Character If char=='1': consecutive++ 3 Add to Result count += consecutive 4 Reset on '0' If char=='0': consecutive=0 Iteration Trace: Char Consec Count Substrings 1 1 1 "1" 1 2 3 "1","11" 1 3 6 "1","11","111" FINAL RESULT All Valid Substrings: "1" "1" "1" "11" "11" "111" Length 1: 3 substrings Length 2: 2 substrings Length 3: 1 substring Formula: n*(n+1)/2 = 3*4/2 = 6 substrings Output: 6 OK Key Insight: For a group of n consecutive 1s, the number of substrings containing only 1s is n*(n+1)/2. Each new '1' adds (consecutive count) new substrings ending at that position. Time: O(n), Space: O(1). Don't forget to apply modulo 10^9 + 7 to handle large results! TutorialsPoint - Number of Substrings With Only 1s | Optimal Solution
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