Count Binary Substrings

Given a binary string s, return the number of non-empty substrings that have the same number of 0s and 1s, where all the 0s are grouped together and all the 1s are grouped together. Substrings that occur several times are counted each time they occur.

30:00

Count Binary Substrings
easy
Free written solution
Topics
Companies

Given a binary string s, return the number of non-empty substrings that have the same number of 0s and 1s, where all the 0s are grouped together and all the 1s are grouped together. Substrings that occur several times are counted each time they occur.

Example 1:
Input: {"s":"00110011"}
Output: 6
Constraints:
  • 1≤s.length≤1051 \leq s.\text{length} \leq 10^5

  • s[i] is either '0' or '1'.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"00110011"}

Read the string as runs of equal characters. A valid substring sits across the border of two neighbouring runs, so we only need run lengths: prev = 0, cur = 1.

0
0
1
1
0
0
1
1
prev run
cur run
credited border

substrings across a border appear here

prev

0

cur

1

total

0

Variables
VariableValue
i0
prev0
cur1
total0
DepthFunction Call
Stack empty
0/13