Problem 365476 · easy · Phase 03 Linear Management & Searching

Balanced Binary Blocks

sliding window · run-length · strings

A tile strip is a string s of '0's and '1's. A substring is balanced if it contains the same number of 0s and 1s and all the 0s are grouped together and all the 1s are grouped together (for example "0011" and "10" are balanced but "0101" is not). Return how many balanced substrings s contains; substrings at different positions count separately even if they read the same.

Examples

Input:  s = "00110011"
Output: 6
Explanation: "0011", "01", "1100", "10", "0011" and "01".

Input:  s = "10101"
Output: 4

Constraints

  • 1 <= len(s) <= 10**5
  • s[i] is '0' or '1'
  • Target complexity: O(n) time; enumerating all substrings (O(n²)) is too slow for the largest tests.

Goals

  • Compress a string into runs of equal characters
  • Count valid substrings from adjacent run lengths
Starting Python…