Count Binary Substrings

Easy

Topics
Two PointersString

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

s0001121304051617
runs0 x21 x20 x21 x2
a runthe next run
A qualifying piece is some 0s followed by some 1s or the reverse, never interleaved, so it always straddles the boundary between two runs taking an equal amount from each side. The 4 runs above give min(2,2)=2 + min(2,2)=2 + min(2,2)=2 = 6.
One cell per character; the chips below are the same string compressed into runs.
Input:  s = "00110011"
Output: 6
Explanation: The qualifying pieces are 0011, 01, 1100, 10, 0011 and 01.

Example 2

s1001120314
runs1 x10 x11 x10 x11 x1
a runthe next run
The 5 runs above give min(1,1)=1 + min(1,1)=1 + min(1,1)=1 + min(1,1)=1 = 4.
Input:  s = "10101"
Output: 4
Explanation: 10, 01, 10 and 01.

Example 3

s000102
runs0 x3
a run
There is only one run, so there is no boundary and the answer is 0.
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

  1. Walk the string, measuring the length of each maximal run of equal digits.
  2. Keep the length of the previous run alongside the current one.
  3. Whenever a run ends, add min(previousRun, thisRun) to the total.
  4. 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  ->  4

Complexity

  • 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 min has to be added after it.
  • Starting current_run at 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 min of 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)
SensAI
Beta
Tap the mic to stop voice mode