Count Balanced Two-Block Substrings in a Binary String
StringsAuto-graded · 26 test casesLast 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:
- The substring contains an equal number of
'0's and'1's. - 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
sis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Observation: Run-Length Boundaries
Compress the string mentally into a sequence of runs — maximal blocks of identical characters. For example:
"00110011"→ runs of lengths[2, 2, 2, 2]"10101"→ runs of lengths[1, 1, 1, 1, 1]
Every valid substring must span exactly one boundary between two adjacent runs. The left half of the substring comes from the tail of one run, and the right half comes from the head of the next run. If those two runs have lengths a and b, you can choose any half-length k where 1 ≤ k ≤ min(a, b), giving exactly min(a, b) valid substrings at that boundary.
Summing min(a, b) over every adjacent run pair gives the answer.
Why This Is Correct
Every valid substring is counted exactly once. A valid substring has one character-change point. Its left block sits entirely within one run and its right block sits entirely within the next run. It maps to a unique boundary and a unique k, so it is counted once.
Everything counted is valid. For any k ≤ min(a, b), taking k characters from the end of run a and k characters from the start of run b produces exactly two solid, equal-length blocks of opposite characters — which is precisely what the problem asks for.
O(1) Space Implementation
Rather than storing the full run array, keep only two integers:
previous_run: length of the run that ended most recentlycurrent_run: length of the run currently being scanned
When a character transition is detected, add min(previous_run, current_run) to the total, then shift current_run into previous_run and reset current_run to 1.
Initializing previous_run = 0 elegantly handles the very first run: the imaginary "empty" run before position 0 contributes min(0, x) = 0, so no special case is needed.
After the loop ends, the last run never triggered a transition, so its boundary contribution is added with a final min(previous_run, current_run).
Worked Example
Tracing "00110011" step by step:
| index | char | event | previous_run | current_run | total |
|---|---|---|---|---|---|
| start | — | init | 0 | 1 | 0 |
| 1 | 0 | extend | 0 | 2 | 0 |
| 2 | 1 | boundary → +min(0,2)=0 | 2 | 1 | 0 |
| 3 | 1 | extend | 2 | 2 | 0 |
| 4 | 0 | boundary → +min(2,2)=2 | 2 | 1 | 2 |
| 5 | 0 | extend | 2 | 2 | 2 |
| 6 | 1 | boundary → +min(2,2)=2 | 2 | 1 | 4 |
| 7 | 1 | extend | 2 | 2 | 4 |
| end | — | +min(2,2)=2 | — | — | 6 |
Complexity
- Time: O(n) — a single left-to-right pass, constant work per character.
- Space: O(1) auxiliary — only three integers are maintained, regardless of input length.
Common Pitfalls
- Brute-force substring enumeration is O(n²) or worse and will time out for inputs of length 10⁵.
- Checking only global character counts wrongly accepts strings like
"0101", where the counts balance but more than two blocks are present. - Omitting the final
minafter the loop causes the last boundary to be skipped —"01"would return 0 instead of 1. - Using
maxinstead ofminovercounts: the shorter run limits how far you can extend into the longer one.
def count_balanced_blocks(s: str) -> int:
previous_run = 0 # length of the run before the current one (0 = no prior run)
current_run = 1 # length of the run that contains s[i]
total = 0
for i in range(1, len(s)):
if s[i] == s[i - 1]:
# Still inside the same run of identical characters.
current_run += 1
else:
# We've hit a boundary between two adjacent runs.
# Each k from 1..min(previous_run, current_run) yields one valid substring,
# but the relevant pairing here is the run that just ended (current_run)
# with the run before it (previous_run).
total += min(previous_run, current_run)
previous_run = current_run
current_run = 1
# The final run never triggers the else-branch above, so its boundary
# with the second-to-last run must be counted here.
return total + min(previous_run, current_run)