463. Count Binary Substrings
You receive a binary string s (only the characters 0 and 1). Return the number of non-empty substrings of s that contain the same count of 0s and 1s, where all the 0s sit together and all the 1s sit together — that is, substrings shaped like 000...111 or 111...000 with both halves equally long.
Count every occurrence separately: if the same-looking substring appears in two different positions, it counts twice.
Example 1:
Input: s = "00110011"
Output: 6
Explanation: The six qualifying substrings are "0011", "01", "1100", "10", "0011" and "01". Note "0011" is counted twice because it starts at two different positions, while "00110011" itself does not qualify (its zeros are split into two blocks).
Example 2:
Input: s = "10101"
Output: 4
Explanation: "10", "01", "10" and "01" each pair one zero with one adjacent one.
Constraints:
- 1 ≤ s.length ≤ 10⁵
- s[i] is '0' or '1'.
Hints:
A qualifying substring is always one block of a repeated character followed immediately by an equally long block of the other character. Its first half must be a maximal-or-shorter run — what does that force the first half's length to be?
Compress s into run lengths, e.g. "00110011" → [2, 2, 2, 2]. How many qualifying substrings live across the border between two adjacent runs of lengths a and b?
Every border between adjacent runs contributes min(a, b) substrings, so the answer is the sum of min over consecutive run lengths — computable in one pass with just two counters.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: s = "00110011"
Expected output: 6