Count Binary Substrings - Problem
Given a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
Example: In string "00110011", valid substrings include "01", "10", "0011", "1100", etc.
Input & Output
Example 1 — Basic Pattern
$
Input:
s = "00110011"
›
Output:
6
💡 Note:
Valid substrings: "01" (at positions 1-2 and 5-6), "10" (at positions 2-3 and 4-5), "0011" (at positions 0-3), "1100" (at positions 2-5). Total = 6 substrings.
Example 2 — Alternating Pattern
$
Input:
s = "10101"
›
Output:
4
💡 Note:
Valid substrings: "01" (at positions 1-2 and 3-4), "10" (at positions 0-1 and 2-3). Each pair of adjacent different characters forms exactly one valid substring.
Example 3 — Single Group
$
Input:
s = "1111"
›
Output:
0
💡 Note:
No valid substrings possible since all characters are the same. We need both 0s and 1s to form valid substrings.
Constraints
- 1 ≤ s.length ≤ 105
- s[i] is either '0' or '1'
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code