In this approach, we maintain two counters to track consecutive groups of 0's and 1's as we move through the string. By comparing these group counts, we can determine the number of valid equal-length substrings.
As we traverse the string, we increment the count for the current group and check if the previous group length is greater than or equal to the current group length. This indicates that we can form a valid substring.
Time Complexity: O(n) because we make a single pass through the string.
Space Complexity: O(1) since we use a constant amount of extra space.
1class Solution:
2 def countBinarySubstrings(self, s: str) -> int:
3 prev, curr, count = 0, 1, 0
4 for i in range(1, len(s)):
5 if s[i] == s[i - 1]:
6 curr += 1
7 else:
8 count += min(prev, curr)
9 prev = curr
10 curr = 1
11 return count + min(prev, curr)
12
13if __name__ == '__main__':
14 sol = Solution()
15 print(sol.countBinarySubstrings("00110011"))
The implementation in Python makes use of similar logic. The countBinarySubstrings
method tracks the sizes of consecutive character blocks and calculates the valid substrings based on these block sizes.
This approach involves creating an array to store the lengths of consecutive 0's and 1's. By iterating through this array, we add the minimum value of each pair to a count, which represents valid substrings.
First, traverse the string to form groups, then iterate through the formed group to compute the valid substring count based on consecutive groups' minimum lengths.
Time Complexity: O(n) - The string is traversed twice, but both passes are O(n).
Space Complexity: O(n) due to the need to store group lengths.
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4
5int countBinarySubstrings(char * s) {
6 int len = strlen(s);
7 int *groups = (int *)malloc(len * sizeof(int));
8 int groupIndex = 0, count = 0;
9 groups[0] = 1;
10
11 for (int i = 1; i < len; i++) {
12 if (s[i] != s[i-1]) {
13 groupIndex++;
14 groups[groupIndex] = 1;
15 } else {
16 groups[groupIndex]++;
17 }
18 }
19
20 for (int i = 1; i <= groupIndex; i++) {
21 count += groups[i-1] < groups[i] ? groups[i-1] : groups[i];
22 }
23
24 free(groups);
25 return count;
26}
27
28int main() {
29 char s[] = "00110011";
30 printf("%d\n", countBinarySubstrings(s));
31 return 0;
32}
In this C implementation, after creating a dynamically sized array to store consecutive group lengths, we compute valid substrings by iterating over these lengths and summing the minimum values of consecutive pairs.