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 INPUT Binary String s: 0 0 1 1 0 0 1 1 0 1 2 3 4 5 6 7 Valid Substrings: "0011" "01" "1100" "10" "0011" "01" Consecutive Groups: 00 11 00 11 Groups: [2, 2, 2, 2] ALGORITHM STEPS 1 Initialize Counters prev=0, curr=1, result=0 2 Scan String Compare adjacent chars 3 On Char Change prev=curr, curr=1 4 Add to Result If prev >= curr: result++ Iteration Trace i=1: prev=0 curr=2 add=0 i=2: prev=2 curr=1 add=1 i=3: prev=2 curr=2 add=1 i=4: prev=2 curr=1 add=1 i=5: prev=2 curr=2 add=1 i=6,7: prev=2 curr=2 add=2 FINAL RESULT Total Valid Substrings: 6 Breakdown by Position: Pos 1-2: "01" [OK] Pos 0-3: "0011" [OK] Pos 2-3: "10" [OK] Pos 2-5: "1100" [OK] Pos 4-5: "01" [OK] Pos 4-7: "0011" [OK] Output: 6 Key Insight: The number of valid substrings between two groups is min(prevGroupLen, currGroupLen). By tracking only the previous and current group lengths, we achieve O(n) time and O(1) space. Each transition between 0s and 1s contributes min(prev, curr) valid substrings to the result. TutorialsPoint - Count Binary Substrings | Single Pass Optimized Approach Time: O(n) Space: O(1)
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