1513. Number of Substrings With Only 1s LeetCode Solution
In this guide, you will get 1513. Number of Substrings With Only 1s LeetCode Solution with the best time and space complexity. The solution to Number of Substrings With Only s problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Number of Substrings With Only s solution in C++
- Number of Substrings With Only s solution in Java
- Number of Substrings With Only s solution in Python
- Additional Resources
Problem Statement of Number of Substrings With Only s
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 1:
Input: s = “0110111”
Output: 9
Explanation: There are 9 substring in total with only 1’s characters.
“1” -> 5 times.
“11” -> 3 times.
“111” -> 1 time.
Example 2:
Input: s = “101”
Output: 2
Explanation: Substring “1” is shown 2 times in s.
Example 3:
Input: s = “111111”
Output: 21
Explanation: Each substring contains only 1’s characters.
Constraints:
1 <= s.length <= 105
s[i] is either '0' or '1'.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
1513. Number of Substrings With Only 1s LeetCode Solution in C++
class Solution {
public:
int numSub(string s) {
constexpr int kMod = 1'000'000'007;
int ans = 0;
int l = -1;
for (int i = 0; i < s.length(); ++i) {
if (s[i] == '0')
l = i; // Handle the reset value.
ans = (ans + i - l) % kMod;
}
return ans;
}
};
/* code provided by PROGIEZ */
1513. Number of Substrings With Only 1s LeetCode Solution in Java
N/A
// code provided by PROGIEZ
1513. Number of Substrings With Only 1s LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.