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.
1#include <stdio.h>
2#include <string.h>
3
4int countBinarySubstrings(char * s) {
5 int prev = 0, curr = 1, count = 0;
6 for (int i = 1; s[i] != '\0'; i++) {
7 if (s[i] == s[i - 1]) {
8 curr++;
9 } else {
10 count += (prev < curr) ? prev : curr;
11 prev = curr;
12 curr = 1;
13 }
14 }
15 return count + ((prev < curr) ? prev : curr);
16}
17
18int main() {
19 char s[] = "00110011";
20 printf("%d\n", countBinarySubstrings(s));
21 return 0;
22}
The above code uses a two-pointer technique to track the lengths of consecutive characters. It keeps track of the current and previous group lengths and increases the output count based on the lesser of the two. This ensures only valid substrings with equal '0's and '1's are counted.
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.
1var countBinarySubstrings = function(s) {
2 let groups = [];
3 let count = 0;
4 let i = 0;
5 let n = s.length;
6 while (i < n) {
7 let ch = s[i];
8 let c = 0;
9 while (i < n && s[i] === ch) {
10 i++;
11 c++;
12 }
13 groups.push(c);
14 }
15
16 for (let j = 1; j < groups.length; j++) {
17 count += Math.min(groups[j - 1], groups[j]);
18 }
19 return count;
20};
21
22console.log(countBinarySubstrings("00110011"));
In this JavaScript solution, an array stores the lengths of consecutive groups of characters and determines the number of balanced substrings by summing up min values of each pair of subsequent group lengths.