Given a binary string str of length N, the task is to find the maximum count of substrings str can be divided into such that all the substrings are balanced i.e. they have equal number of 0s and 1s. If it is not possible to split str satisfying the conditions then print -1.
Input: str = “0100110101”
The required substrings are “01”, “0011”, “01” and “01”.
Input: str = “0111100010”
Approach: Initialize count = 0 and traverse the string character by character and keep track of the number of 0s and 1s so far, whenever the count of 0s and 1s become equal increment the count. If the count of 0s and 1s in the original string is not equal then print -1 else print the value of count after the traversal of the complete string.
Below is the implementation of the above approach:
Time complexity: O(N) where N is the length of string
Space Complexity: O(1)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Number of substrings with odd decimal value in a binary string
- Split the string into substrings using delimiter
- Given a binary string, count number of substrings that start and end with 1.
- Minimum number of swaps to make two binary string equal
- Count of substrings of a binary string containing K ones
- Count Substrings with equal number of 0s, 1s and 2s
- Counting even decimal value substrings in a binary string
- Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1
- Number of ways to split a binary number such that every part is divisible by 2
- Number of substrings of a string
- Sum of all substrings of a string representing a number | Set 1
- Number of substrings of one string present in other
- Number of even substrings in a string of digits
- Number of substrings divisible by 6 in a string of integers
- Split a string in equal parts such that all parts are palindromes
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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 : princiraj1992