Given a binary string str of 0’s and 1’s only. The task is to count the total numbers of substrings of string str such that each substring has an equal number of consecutive 0’s and 1’s in it.
Input: str = “010011”
The substrings with consecutive 0’s and 1’s are “01”, “10”, “0011”, “01”. Hence, the count is 4.
The two “01” are at different positions: [0, 1] and [3, 4].
“010011” has the same number of 0’s and 1’s but they are not consecutive.
Input: str = “0001110010”
The substrings with consecutive 0’s and 1’s are “000111”, “0011”, “01”, “1100”, “10”, “01”, “10”.
- Count the number of consecutive 0’s (or 1’s) from start of the string.
- Then count the number of consecutive 1’s (or 0’s) from the position in the string str where count of 0’s (or 1’s) ends.
- The total number of substrings with consecutive 0’s and 1’s is the minimum of the count of consecutive 0’s and 1’s found in above two steps.
- Repeat the above steps till the end of the string str.
Below is the implementation of the above approach:
Time Complexity: O(N), where N = length of string.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Count Substrings with equal number of 0s, 1s and 2s
- Count of substrings whose Decimal equivalent is greater than or equal to K
- Split the binary string into substrings with equal number of 0s and 1s
- Split a given string into substrings of length K with equal sum of ASCII values
- Count of binary strings of length N with even set bit count and at most K consecutive 1s
- Count substrings that contain all vowels | SET 2
- Count all substrings having character K
- Count substrings with same first and last characters
- Count of substrings of a binary string containing K ones
- Count of total anagram substrings
- Count of substrings formed using a given set of characters only
- Number of substrings with count of each character as k
- Count of substrings which contains a given character K times
- Count of substrings consisting only of vowels
- Count substrings with each character occurring at most k times
- Count of substrings of length K with exactly K distinct characters
- Recursive solution to count substrings with same first and last characters
- Count of all unique substrings with non-repeating characters
- Count all Prime Length Palindromic Substrings
- Count number of substrings with exactly k distinct characters
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Yash_R