Split the binary string into substrings with equal number of 0s and 1s
Last Updated :
30 Mar, 2023
Given a binary string str of length N, the task is to find the maximum count of consecutive 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.
Example:
Input: str = "0100110101"
Output: 4
The required substrings are "01", "0011", "01" and "01".
Input: str = "0111100010"
Output: 3
Input: str = "0000000000"
Output: -1
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. As in the given question, if it is not possible to split string then on that time count of 0s must not be equal to count of 1s then return -1 else print the value of count after the traversal of the complete string.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the count
// of maximum substrings str
// can be divided into
int maxSubStr(string str, int n)
{
// To store the count of 0s and 1s
int count0 = 0, count1 = 0;
// To store the count of maximum
// substrings str can be divided into
int cnt = 0;
for (int i = 0; i < n; i++) {
if (str[i] == '0') {
count0++;
}
else {
count1++;
}
if (count0 == count1) {
cnt++;
}
}
// It is not possible to
// split the string
if (count0!=count1) {
return -1;
}
return cnt;
}
// Driver code
int main()
{
string str = "0100110101";
int n = str.length();
cout << maxSubStr(str, n);
return 0;
}
Java
// Java implementation of the above approach
class GFG
{
// Function to return the count
// of maximum substrings str
// can be divided into
static int maxSubStr(String str, int n)
{
// To store the count of 0s and 1s
int count0 = 0, count1 = 0;
// To store the count of maximum
// substrings str can be divided into
int cnt = 0;
for (int i = 0; i < n; i++)
{
if (str.charAt(i) == '0')
{
count0++;
}
else
{
count1++;
}
if (count0 == count1)
{
cnt++;
}
}
// It is not possible to
// split the string
if (count0 != count1)
{
return -1;
}
return cnt;
}
// Driver code
public static void main(String []args)
{
String str = "0100110101";
int n = str.length();
System.out.println(maxSubStr(str, n));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 implementation of the approach
# Function to return the count
# of maximum substrings str
# can be divided into
def maxSubStr(str, n):
# To store the count of 0s and 1s
count0 = 0
count1 = 0
# To store the count of maximum
# substrings str can be divided into
cnt = 0
for i in range(n):
if str[i] == '0':
count0 += 1
else:
count1 += 1
if count0 == count1:
cnt += 1
# It is not possible to
# split the string
if count0 != count1:
return -1
return cnt
# Driver code
str = "0100110101"
n = len(str)
print(maxSubStr(str, n))
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to return the count
// of maximum substrings str
// can be divided into
static int maxSubStr(String str, int n)
{
// To store the count of 0s and 1s
int count0 = 0, count1 = 0;
// To store the count of maximum
// substrings str can be divided into
int cnt = 0;
for (int i = 0; i < n; i++)
{
if (str[i] == '0')
{
count0++;
}
else
{
count1++;
}
if (count0 == count1)
{
cnt++;
}
}
// It is not possible to
// split the string
if (count0 != count1)
{
return -1;
}
return cnt;
}
// Driver code
public static void Main(String []args)
{
String str = "0100110101";
int n = str.Length;
Console.WriteLine(maxSubStr(str, n));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// JavaScript implementation of the approach
// Function to return the count
// of maximum substrings str
// can be divided into
function maxSubStr(str, n)
{
// To store the count of 0s and 1s
var count0 = 0, count1 = 0;
// To store the count of maximum
// substrings str can be divided into
var cnt = 0;
for (var i = 0; i < n; i++) {
if (str[i] == '0') {
count0++;
}
else {
count1++;
}
if (count0 == count1) {
cnt++;
}
}
// It is not possible to
// split the string
if (count0 != count1) {
return -1;
}
return cnt;
}
// Driver code
var str = "0100110101";
var n = str.length;
document.write( maxSubStr(str, n));
</script>
Time complexity: O(N) where N is the length of the string
Space Complexity: O(1)
Another approach using Stack :
Approach: Similar to balanced parenthesis approach using stack, we keep inserting if top of stack matches with traversing character. we keep popping when its not matching with top of stack. Whenever stack is empty, it means we got a balanced substring. In this case, we increase answer variable. At last after complete traversal, we will check if stack is empty or not. If yes, it means everything is balanced out. If not, it means it's not balanced.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int maxSubStr(string str, int n)
{
//similar to balanced paranthesis approach
//we insert similar elements and pop when different element seen
//finally checking if stack will be empty or not at last
//if empty, it is balanced
int ans=0;
int i=0;
stack<int>s;
s.push(str[i]);
i++;
while(i<str.size()){
while(i<str.size()&&s.size()&&i<str.size()&&(s.top()!=str[i])){
s.pop();
i++;
}
if(s.empty()){
ans++;
}
while((i<str.size())&&(s.empty()||s.top()==str[i])){
s.push(str[i]);
i++;
}
}
if(s.empty())
return ans;
return -1;
}
// Driver code
int main()
{
string str = "0100110101";
int n = str.length();
cout << maxSubStr(str, n);
return 0;
}
Java
import java.util.*;
class Main
{
static int maxSubStr(String str, int n)
{
// similar to balanced paranthesis approach
// we insert similar elements and pop when different element seen
// finally checking if stack will be empty or not at last
// if empty, it is balanced
int ans = 0;
int i = 0;
Stack<Character> s = new Stack<>();
s.push(str.charAt(i));
i++;
while(i<str.length()){
while(i<str.length() && !s.empty() && s.peek()!=str.charAt(i)){
s.pop();
i++;
}
if(s.empty()){
ans++;
}
while(i<str.length() && (s.empty() || s.peek()==str.charAt(i))){
s.push(str.charAt(i));
i++;
}
}
if(s.empty())
return ans;
return -1;
}
// Driver code
public static void main(String[] args)
{
String str = "0100110101";
int n = str.length();
System.out.println(maxSubStr(str, n));
}
}
// This code is contributed by anskalyan3
Python3
def maxSubStr(s: str) -> int:
ans = 0
i = 0
stack = [s[i]]
i += 1
while i < len(s):
while i < len(s) and stack and i < len(s) and stack[-1] != s[i]:
stack.pop()
i += 1
if not stack:
ans += 1
while i < len(s) and (not stack or stack[-1] == s[i]):
stack.append(s[i])
i += 1
if not stack:
return ans
return -1
# Driver code
str = "0100110101"
print(maxSubStr(str))
# This code is contributed by Aditya Sharma
C#
using System;
using System.Collections.Generic;
public class MaxSubStrSolution
{
public static int MaxSubStr(string str, int n)
{
// similar to balanced paranthesis approach
// we insert similar elements and pop when different element seen
// finally checking if stack will be empty or not at last
// if empty, it is balanced
int ans = 0;
int i = 0;
Stack<char> s = new Stack<char>();
s.Push(str[i]);
i++;
while (i < str.Length)
{
while (i < str.Length && s.Count > 0 && i < str.Length && s.Peek() != str[i])
{
s.Pop();
i++;
}
if (s.Count == 0)
{
ans++;
}
while (i < str.Length && (s.Count == 0 || s.Peek() == str[i]))
{
s.Push(str[i]);
i++;
}
}
if (s.Count == 0)
{
return ans;
}
return -1;
}
// Driver code
public static void Main()
{
string str = "0100110101";
int n = str.Length;
Console.WriteLine(MaxSubStr(str, n));
}
}
JavaScript
const maxSubStr = (str, n) => {
//similar to balanced paranthesis approach
//we insert similar elements and pop when different element seen
//finally checking if stack will be empty or not at last
//if empty, it is balanced
let ans = 0;
let i = 0;
let s = [];
s.push(str[i]);
i++;
while(i < str.length){
while(i < str.length && s.length > 0 && s[s.length-1] !== str[i]){
s.pop();
i++;
}
if(s.length === 0)
ans++;
while(i < str.length && (s.length === 0 || s[s.length-1] === str[i])){
s.push(str[i]);
i++;
}
}
if(s.length === 0)
return ans;
return -1;
}
// Driver code
let str = "0100110101";
let n = str.length;
console.log(maxSubStr(str, n));
Time complexity: O(n), where n is the length of the input string. This is because the code iterates over the string once.
Auxiliary Space: O(n), the above code is using a stack to store the elements of string, so over all complexity is O(n).
Similar Reads
Generate Binary String with equal number of 01 and 10 Subsequence Given an integer N (N > 2), the task is to generate a binary string of size N that consists of equal numbers of "10" & "01" subsequences and also the string should contain at least one '0' and one '1' Note: If multiple such strings exist, print any. Examples: Input: 4Output: 0110Explanation :
7 min read
Number of substrings with odd decimal value in a binary string Given a binary string containing only 0's and 1's. Write a program to find number of sub-strings of this string whose decimal representation is odd. Examples : Input : 101 Output : 3 Explanation : Substrings with odd decimal representation are: {1, 1, 101} Input : 1101 Output : 6 Explanation : Subst
6 min read
Count of substrings that start and end with 1 in given Binary String Given a binary string, count the number of substrings that start and end with 1. Examples: Input: "00100101"Output: 3Explanation: three substrings are "1001", "100101" and "101" Input: "1001"Output: 1Explanation: one substring "1001" Recommended PracticeCount SubstringsTry It!Count of substrings tha
12 min read
Count of substrings with equal ratios of 0s and 1s till ith index in given Binary String Given a binary string S, the task is to print the maximum number of substrings with equal ratios of 0s and 1s till the ith index from the start. Examples: Input: S = "110001"Output: {1, 2, 1, 1, 1, 2}Explanation: The given string can be partitioned into the following equal substrings: Valid substrin
9 min read
Count Substrings with equal number of 0s, 1s and 2s Given a string that consists of only 0s, 1s and 2s, count the number of substrings that have an equal number of 0s, 1s, and 2s.Examples: Input: str = â0102010âOutput: 2Explanation: Substring str[2, 4] = â102â and substring str[4, 6] = â201â has equal number of 0, 1 and 2Input: str = "102100211"Outpu
9 min read
Count of substrings in a Binary String that contains more 1s than 0s Given a binary string s, the task is to calculate the number of such substrings where the count of 1's is strictly greater than the count of 0's. Examples Input: S = "110011"Output: 11Explanation: Substrings in which the count of 1's is strictly greater than the count of 0's are { S[0]}, {S[0], S[1]
15+ min read
Split a Binary String such that count of 0s and 1s in left and right substrings is maximum Given a binary string, str of length N, the task is to find the maximum sum of the count of 0s on the left substring and count of 1s on the right substring possible by splitting the binary string into two non-empty substrings. Examples: Input: str = "000111" Output: 6 Explanation: Splitting the bina
7 min read
Length of the longest substring with equal 1s and 0s Given a binary string. We need to find the length of the longest balanced substring. A substring is balanced if it contains an equal number of 0 and 1. Examples: Input : input = 110101010Output : Length of longest balanced sub string = 8 Input : input = 0000Output : Length of longest balanced sub st
10 min read
Count Substrings with number of 0s and 1s in ratio of X : Y Given a binary string S, the task is to count the substrings having the number of 0s and 1s in the ratio of X : Y Examples: Input: S = "010011010100", X = 3, Y = 2Output: 5Explanation: The index range for the 5 substrings are: (0, 4), (2, 6), (6, 10), (7, 11), (2, 11) Input: S = "10010101", X = 1, Y
7 min read
Count ways to split a Binary String into three substrings having equal count of zeros Given binary string str, the task is to count the total number of ways to split the given string into three non-overlapping substrings having the same number of 0s. Examples: Input: str = "01010" Output: 4 Explanation: The possible splits are: [0, 10, 10], [01, 01, 0], [01, 0, 10], [0, 101, 0] Input
15+ min read