Count Binary Substrings - Problem
Given a binary string s, find all valid substrings that satisfy these conditions:
- Have an equal number of 0's and 1's
- All 0's are grouped together consecutively
- All 1's are grouped together consecutively
Return the total count of such substrings. Note that substrings appearing multiple times should be counted each time they occur.
Example: In "00110", valid substrings are "0011" and "01" (appears twice), giving us a total count of 3.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "00110"
โบ
Output:
3
๐ก Note:
Valid substrings are: "0011" (1 occurrence), "01" (2 occurrences at positions 1-2 and 2-3). Total = 3.
example_2.py โ Alternating Pattern
$
Input:
s = "10101"
โบ
Output:
4
๐ก Note:
Valid substrings are: "10" (appears 2 times), "01" (appears 2 times). Each has equal 0s and 1s with proper grouping.
example_3.py โ Single Character
$
Input:
s = "1"
โบ
Output:
0
๐ก Note:
No valid substrings possible since we need at least one 0 and one 1 to form a valid substring.
Constraints
- 1 โค s.length โค 105
- s[i] is either '0' or '1'
Visualization
Tap to expand
Understanding the Visualization
1
Group Recognition
Identify consecutive runs: '00110' becomes groups [2ร0, 2ร1, 1ร0]
2
Bridge Building
Between adjacent groups, we can build min(group1, group2) bridges
3
Count Bridges
Each bridge represents a valid substring: min(2,2)=2 plus min(2,1)=1
4
Final Count
Sum all bridges: 2 + 1 = 3 valid substrings
Key Takeaway
๐ฏ Key Insight: Between any two adjacent groups of different characters, the number of valid substrings equals the minimum of their sizes - this transforms a cubic brute force into a linear solution!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code