Count Binary Substrings

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Count Binary Substrings

Approach

Compress the string into run lengths of consecutive equal characters and add the minimum of each adjacent run pair.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Run-Length Grouping

Why It Works

A valid substring across a 0/1 boundary can use at most the shorter adjacent run length.

Updated Feb 2026