Count Binary Substrings
Easy
Topics
Given a binary string s, count the non-empty substrings that have equal numbers of 0s and 1s, with all the 0s and all the 1s grouped consecutively.
So "0011" and "10" qualify, while "0101" does not — its counts are equal but its digits are not grouped. Substrings at different positions count separately even if they read the same.
Example 1
Input: s = "00110011" Output: 6 Explanation: The qualifying pieces are 0011, 01, 1100, 10, 0011 and 01.
Example 2
Input: s = "10101" Output: 4 Explanation: 10, 01, 10 and 01.
Example 3
Input: s = "000" Output: 0 Explanation: With no 1 anywhere, no piece can have equal counts.
Constraints
- 1 <= s.length <= 10^5
- s[i] is either 0 or 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
The grouping requirement is far stronger than it looks. A qualifying substring is some 0s followed by some 1s, or some 1s followed by some 0s — nothing else. That means it always sits exactly on the boundary between two runs, taking some of the run on the left and an equal amount of the run on the right.
So the question is not about substrings at all, it is about adjacent pairs of runs. If the runs either side of a boundary have lengths 3 and 2, the qualifying substrings there are the ones taking 1+1 and 2+2 — two of them, which is min(3, 2).
Compress the string into its run lengths and the answer is the sum of min over every adjacent pair. A string of length n has at most n runs, so this is one pass and does not even need the list of lengths kept.
Approach
- Walk the string, measuring the length of each maximal run of equal digits.
- Keep the length of the previous run alongside the current one.
- Whenever a run ends, add
min(previousRun, thisRun)to the total. - Remember to count the boundary between the last two runs, which the loop reaches when the string ends.
Walkthrough
s = "00110011"
runs: 00 11 00 11
lengths 2 2 2 2
boundaries and their contributions
00 | 11 min(2,2) = 2 -> "0011" and "01"
11 | 00 min(2,2) = 2 -> "1100" and "10"
00 | 11 min(2,2) = 2 -> "0011" and "01"
total 6
---
s = "10101"
runs 1 0 1 0 1
lengths 1 1 1 1 1
boundaries min = 1 each, four of them -> 4Complexity
- Time — O(n): one pass, with no storage of the run lengths.
- Space — O(1): two counters.
Common Pitfalls
- Forgetting the final boundary. The loop ends while the last run is still open, so one
minhas to be added after it. - Starting
current_runat 0 rather than 1. The first character is already a run of one. - Counting every substring with equal 0s and 1s.
"0101"has equal counts and does not qualify, which is what the grouping requirement excludes. - Adding
minof all run lengths, or the product. It is the minimum of each adjacent pair, summed over boundaries.
Full Solution — all languages
class Solution:
def countBinarySubstrings(self, s):
total = 0
previous_run = 0
current_run = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
current_run += 1
else:
total += min(previous_run, current_run)
previous_run = current_run
current_run = 1
return total + min(previous_run, current_run)import java.util.*;
class Solution {
public int countBinarySubstrings(String s) {
int total = 0, previousRun = 0, currentRun = 1;
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(i - 1)) currentRun++;
else {
total += Math.min(previousRun, currentRun);
previousRun = currentRun;
currentRun = 1;
}
}
return total + Math.min(previousRun, currentRun);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int countBinarySubstrings(string s) {
int total = 0, previousRun = 0, currentRun = 1;
for (size_t i = 1; i < s.size(); i++) {
if (s[i] == s[i - 1]) currentRun++;
else {
total += min(previousRun, currentRun);
previousRun = currentRun;
currentRun = 1;
}
}
return total + min(previousRun, currentRun);
}
};/**
* @param {string} s
* @return {number}
*/ var countBinarySubstrings = function(s) {
let total = 0, previousRun = 0, currentRun = 1;
for (let i = 1; i < s.length; i++) {
if (s[i] === s[i - 1]) currentRun++;
else {
total += Math.min(previousRun, currentRun);
previousRun = currentRun;
currentRun = 1;
}
}
return total + Math.min(previousRun, currentRun);
};