Similar Problems
Similar Problems not available
Number Of Substrings With Only 1s - Leetcode Solution
Companies:
LeetCode: Number Of Substrings With Only 1s Leetcode Solution
Difficulty: Medium
Problem:
The problem Number of Substrings With Only 1s asks us to count the number of contiguous substrings in a given binary string that contains only 1s.
For example, if the input binary string is "00110011", then the output should be 6, as there are six substrings with only 1s: "11", "111", "1111", "11", "11", and "1".
Approach:
We can solve this problem efficiently using the sliding window technique. The idea is to move a window of size k (where k is the length of the substring with only 1s) over the input string and count the number of valid substrings.
The steps for the sliding window approach are as follows:
-
Initialize two variables, start and end, to 0.
-
Set a variable count to 0, which will store the number of valid substrings.
-
Loop over the input string.
-
If a character is '1', increment the window end by 1.
-
If a character is '0', reset the window start to end and move the window end by 1.
-
Check if the current window contains only 1s. If yes, then increment the count by the length of the window.
-
After the loop, return the count.
Code:
Here's the Python code for the above algorithm:
class Solution: def numSub(self, s: str) -> int: start, end, count = 0, 0, 0 n = len(s) while end < n: if s[end] == '1': end += 1 elif s[end] == '0': start = end end += 1 if '1' * (end - start) == s[start:end]: count += end - start return count
Time Complexity:
The time complexity of the above algorithm is O(n), where n is the length of the input string.
Space Complexity:
The space complexity of the above algorithm is O(1), as we are not using any additional data structures to solve the problem.
Number Of Substrings With Only 1s Solution Code
1