KatInterview

Count Balanced Two-Block Substrings in a Binary String

StringsAuto-graded · 26 test cases
MediumAuto-gradedStringsstringstwo-pointersrun-length-encoding

Last updated

Tests whether a candidate can group consecutive identical characters into runs and use adjacent run lengths to efficiently count valid balanced substrings.

Count Balanced Two-Block Substrings in a Binary String

You are given a string s made up entirely of '0's and '1's. Your task is to count how many substrings satisfy both of the following conditions:

  1. The substring contains an equal number of '0's and '1's.
  2. Every '0' in the substring appears together in one unbroken block, and every '1' appears together in one unbroken block — the two blocks sit side by side.

In other words, the substring must look like k copies of one character immediately followed by k copies of the other character (for some k ≥ 1). Patterns like "01", "10", "0011", "1100", "000111" are all valid; something like "0101" is not, because the characters alternate rather than forming two solid blocks.

Substrings that start at different positions are always treated as separate occurrences, even if they contain the same characters.

Return the total count of such substrings.

Constraints

  • 1 <= len(s) <= 10^5
  • Every character in s is either '0' or '1'

Examples

Example 1

Input: count_balanced_blocks('00110011')

Output: 6

Example 2

Input: count_balanced_blocks('10101')

Output: 4

Hints

Hint 1

Think about compressing the string into a list of run lengths — consecutive identical characters form one run. How does a valid substring relate to two adjacent runs?

Hint 2

At the boundary between a run of length a and a run of length b, you can form min(a, b) valid substrings: take the last k characters of the left run and the first k characters of the right run, for each k from 1 up to min(a, b).

Hint 3

You don't need to store all run lengths at once. Try keeping track of just the previous run length and the current run length as you scan left to right, and accumulate the answer at each transition between runs.