KatInterview

Count Balanced Two-Block Binary Substrings

StringsAuto-graded · 24 test cases
EasyAuto-gradedStringsstringstwo-pointersrun-length

Last updated

Count substrings of a binary string made of one block of equal characters followed by a block of the other character, with both blocks the same length.

You are given a binary string s that contains only the characters '0' and '1'.

Count the non-empty substrings of s that have this shape: a block of identical characters immediately followed by a block of the opposite character, where both blocks have the same length. Equivalently, a qualifying substring is k copies of one digit followed by k copies of the other digit, for some k >= 1. Examples of the shape are "01", "10", "0011", and "111000".

A substring such as "0101" does not qualify. Its counts are equal, but the zeros and ones are interleaved instead of forming two blocks.

Substrings are counted by position. If the same text appears at several different positions in s, each position counts separately.

Return the total number of qualifying substrings. If s is empty or has no qualifying substring, return 0.

Constraints

  • 0 <= len(s) <= 10^5
  • s contains only the characters '0' and '1'.
  • The function returns a single non-negative integer.

Examples

Example 1

Input: count_two_block_substrings('0011')

Output: 2

Example 2

Input: count_two_block_substrings('10101')

Output: 4

Example 3

Input: count_two_block_substrings('00110011')

Output: 6

Example 4

Input: count_two_block_substrings('0000')

Output: 0

Hints

Hint 1

Look at the string as a sequence of maximal runs of the same character. What can a qualifying substring look like in terms of those runs?

Hint 2

Every qualifying substring sits across exactly one boundary between two neighbouring runs. Given the lengths of those two runs, how many different values of k are possible?

Hint 3

Each pair of neighbouring runs with lengths a and b contributes min(a, b). Track only the previous run length and the current run length while scanning, and remember to add the final pair after the loop.