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
0 0 1 1 0Island 12 ร— '0'Island 22 ร— '1'Island 31 ร— '0'Bridge: min(2,2)=2Bridge: min(2,1)=1Valid Substrings Found"01", "0011", "10"Total Count: 3
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!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~15 min Avg. Time
845 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