Leetcode 1513: Number of Substrings With Only 1s

grid47
grid47
Exploring patterns and algorithms
Jun 8, 2024 5 min read

Given a binary string s, return the number of substrings that consist entirely of ‘1’s. Since the result can be large, return the answer modulo (10^9 + 7).
Problem
Approach
Steps
Complexity
Input: The input consists of a binary string s, where each character is either '0' or '1'.
Example: s = "1010101"
Constraints:
• 1 <= s.length <= 10^5
• s[i] is either '0' or '1'.
Output: Return the number of substrings that contain only '1's modulo (10^9 + 7).
Example: 9
Constraints:
• Return the result modulo (10^9 + 7).
Goal: The goal is to calculate the total number of substrings consisting only of '1's. This can be done by grouping consecutive '1's together and applying the formula for the number of substrings from a sequence of length n: ( rac{n(n+1)}{2} ).
Steps:
• Step 1: Traverse the string to find groups of consecutive '1's.
• Step 2: For each group of consecutive '1's, calculate the number of substrings using the formula ( rac{n(n+1)}{2} ), where n is the length of the group.
• Step 3: Sum all the values from step 2 and take the result modulo (10^9 + 7).
Goal: The binary string must meet the constraints outlined in the input representation.
Steps:
• 1 <= s.length <= 10^5
• s[i] is either '0' or '1'.
Assumptions:
• The string contains at least one character.
• The string is composed only of '0' and '1'.
Input: s = "1010101"
Explanation: In this case, we can see that there are multiple occurrences of '1'. The valid substrings consist of individual '1's, pairs of '1's, and triplets of '1's, totaling 9 valid substrings.

Input: s = "0001"
Explanation: Only one substring consisting of '1' exists, so the output is 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus