DSA problem
Count Binary Substrings
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.
A substring is a contiguous sequence of characters within the string. For example, in the string "00110011", valid substrings include "0011", "01", "1100", "10", "0011", and "01", because the zeros and ones forming each substring are grouped together and equal in count.
Examples
Example 1
Input:
s = "00110011"Output:
6Explanation: There are 6 substrings that have equal number of consecutive 0s and 1s: "0011", "01", "1100", "10", "0011", and "01". Some substrings repeat and are counted each time they occur.
Example 2
Input:
s = "10101"Output:
4Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 0s and 1s.
Constraints
- 1 <= s.length <= 10^5
- s[i] is either '0' or '1'.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.