696. Count Binary Substrings
Easy ↗ Open on LeetCode Source: Misc
Quick review
- Pattern
- Two Pointers
- Time
- O(n)
- Space
- O(n)
Standard Solution (C++)
SummaryGiven a binary string, count the number of non-empty substrings that contain an equal number of consecutive 0s and 1s (and all the 0s and 1s must be grouped together, e.g. "0011" or "1100").
Approach
- Compress the string into run-length groups: track how many consecutive identical characters appear in each contiguous run.
- For every adjacent pair of runs,
min(run[i], run[i+1])substrings of the required form can be formed, because the shorter run is the bottleneck. - Keep only the previous run count to avoid the auxiliary vector, reducing space to O(1).
- A single linear scan suffices, making the algorithm O(n) time.
#include <string>
using namespace std;
class Solution {
public:
int countBinarySubstrings(string s) {
int result = 0;
int prev = 0; // length of the run before the current one
int cur = 1; // length of the current run
for (int i = 1; i < (int)s.size(); ++i) {
if (s[i] == s[i - 1]) {
++cur;
} else {
// Transition: the previous run is now fully known
prev = cur;
cur = 1;
}
// At every position, if prev >= cur there is a valid substring
// ending here (cur chars of one kind + cur chars of the other).
if (prev >= cur) ++result;
}
return result;
}
}; Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int countBinarySubstrings(string s) {
vector<int> groups;
char prev=s[0];
int count=0;
int i=0;
while(i<s.length()){
while(s[i]==prev){
++count;
++i;
}
prev=s[i];
groups.push_back(count);
count=0;
}
int res=0;
for(int i=0; i<groups.size()-1; ++i){
res+=std::min(groups[i], groups[i+1]);
}
return res;
}
};
// Time Complexity: O(n)
// Space Complexity: O(n) Time O(n) Space O(n)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.