# Count Binary Substrings

# Problem Statement:-

Give a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.

Substrings that occur multiple times are counted the number of times they occur.

Example 1:-

Input: s = "00110011"

Output: 6

Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".

Notice that some of these substrings repeat and are counted the number of times they occur. Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.

# Approach

We take two variables prev and the next. prev is responsible for keeping track of contiguous same characters whether '0 or '1' until the character changes from '0' to '1' or '1' to '0'. next is responsible for keeping track of contiguous same characters after variable changes whether it is '0' or '1'. Whenever character changes, we interchange prev and next and set next to 1 as we will be counting the number of contiguous changed characters now. If prev is greater than next at any point of time, we can form contiguous substrings, therefore, we increment the count.

```
class Solution {
public:
int countBinarySubstrings(string s) {
int prev=0;
int next=1;
int count=0;
int n=s.size();
for (int i=1;i<n;i++){
if (s[i]==s[i-1])
next++;
else{
prev=next;
next=1;
}
if(prev>=next)
count++;
}
return count;
}
};
```

Time Complexity: O(n)

Space Complexity: O(1)