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
Count Binary Substrings: "00110" → 3 valid substrings00110Group 1 (2)Group 2 (2)Group 3 (1)Valid substrings found:"01" at pos 1-2"0011" at pos 0-3"10" at pos 3-4Total Count: 3Groups [2,2,1] → min(2,2) + min(2,1) = 2 + 1 = 3
Understanding the Visualization
1
Input String
Binary string with consecutive groups of 0s and 1s
2
Find Groups
Identify consecutive runs of same characters
3
Count Valid Substrings
Between adjacent groups, min(group1_size, group2_size) valid substrings
Key Takeaway
🎯 Key Insight: Valid substrings form only at boundaries between consecutive groups, with count = min(group_size1, group_size2)
Asked in
Facebook 35 Google 28 Microsoft 22
89.5K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen