Count Binary Substrings (LeetCode 696): Solution and Explanation

Easy
Two Pointers
String

Count substrings of a binary string that are a block of one bit followed by an equal-length block of the other bit, such as "01", "1100" or "000111". Every such substring sits across the border of two neighbouring runs.

Intuition

A valid substring looks like k zeros then k ones, or k ones then k zeros. The k equal characters on each side must be part of two neighbouring runs, so the substring is centred on the border between those runs.

If the run on the left has length a and the run on the right has length b, you can take k characters from each side for every k from 1 up to min(a, b). That is exactly min(a, b) substrings, and no other substring crosses that border.

So the answer is the sum of min(a, b) over every pair of neighbouring runs. While scanning you only need the length of the run that just ended (prev) and the one in progress (cur).

Approach: Previous and current run length

  1. Set prev = 0, cur = 1 and total = 0.
  2. For i from 1 to n - 1, if s[i] equals s[i - 1] the current run grows: cur += 1.
  3. Otherwise a run just ended: add min(prev, cur) to total, then set prev = cur and cur = 1.
  4. After the loop, the last border still needs its share: return total + min(prev, cur).

Step-by-step example

s = "00110011"
  1. The runs are 00, 11, 00, 11, so the run lengths are 2, 2, 2, 2.
  2. At index 2 the first run of 0s ends. prev is 0, so it adds nothing. Now prev = 2.
  3. At index 4 the run of 1s ends: min(2, 2) = 2, giving "01" and "0011". total = 2.
  4. At index 6 the second run of 0s ends: min(2, 2) = 2, giving "10" and "1100". total = 4.
  5. The string ends inside the last run of 1s: min(2, 2) = 2 more. The answer is 6.

Code: Python, Java, C++

1class Solution:
2    def countBinarySubstrings(self, s: str) -> int:
3        prev, cur, total = 0, 1, 0
4        for i in range(1, len(s)):
5            if s[i] == s[i - 1]:
6                cur += 1
7            else:
8                total += min(prev, cur)
9                prev, cur = cur, 1
10        return total + min(prev, cur)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is compared with its neighbour once.

Space

O(1)

Only prev, cur and total are kept; the run lengths are never stored as a list.

Other approaches

Group lengths array (time O(n), space O(n))

First build the list of run lengths, then sum min(groups[i - 1], groups[i]). It is the same idea in two passes and is easier to read, at the cost of O(n) memory.

Expand from every border (time O(n), space O(1))

At each index where the bit changes, expand left and right while the characters keep matching their side. Each expansion is bounded by the shorter run, so the total work is still linear.

Check every substring (time O(n^2), space O(1))

Test every even-length substring for the k-then-k shape. It is correct but quadratic or worse, far too slow for n = 10^5.

Common mistakes

  • Forgetting the last border. The loop only adds when a run ends, and the final run ends at the end of the string.
  • Counting substrings like "0101" or "0110" that have equal counts but scattered bits. Only one run of each bit is allowed.
  • Starting cur at 0 instead of 1. The first character already forms a run of length 1.
  • Counting distinct substrings. Repeated substrings at different positions each count.

Frequently asked questions

Why is it min(prev, cur) and not prev + cur?

A valid substring takes the same number of characters from both runs, so k cannot exceed the shorter run. Each k from 1 to that limit gives exactly one substring.

Can a substring span three runs?

No. It would contain two separate groups of the same bit, which breaks the rule that all 0s and all 1s are grouped together.

What does a string with only one run return?

Zero. prev stays 0, so min(prev, cur) is 0 at the end.