Longest balanced binary substring with equal count of 1s and 0s
Last Updated :
06 Dec, 2021
Given a binary string str[] of size N. The task is to find the longest balanced substring. A substring is balanced if it contains an equal number of 0 and 1.
Examples:
Input: str = "110101010"
Output: 10101010
Explanation: The formed substring contain equal count of 1 and 0 i.e, count of 1 and 0 is same equal to 4.
Input: str = "0000"
Output: -1
Naive Approach: A simple solution is to use two nested loops to generate every substring. And a third loop to count a number of 0s and 1s in the current substring. Then print the longest substring among them.
Time Complexity: O(N^3)
Auxiliary Space: O(1)
Efficient solution: With the help of precomputation, store the difference between the count of 0s and the count of 1s from start till current index. This difference can then be used to determine the longest substring with equal 0s and 1s, as the longest distance between any duplicate values in the difference array. Use a Map-based hashing to do precomputation. Follow the steps below to solve the problem:
- Initialize the map<int, int> m[].
- Set the value of m[0] as -1.
- Initialize the variables count_0, count_1, res, start and end.
- Traverse the string str[] using the variable i and perform the following tasks:
- Keep the track of counts of 1s and 0s as count_1 and count_0 respectively.
- See if the current difference between count_1 and count_0 is already there in the map m[] or not. If yes, then perform the following tasks:
- The substring from the previous appearance and current index has same number of 0s and 1s.
- If the current found substring's length is greater than res then set the found substring as the answer so far.
- If it is appearing for the first time, store the current difference and the current index in the map i.e, m[count_1 - count_0] equals i.
- If count_0 and count_1 are both 0, then print -1.
- Otherwise, print the substring from start to end.
Below is the implementation of the above approach.
C++
// C++ for finding length
// of longest balanced substring
#include <bits/stdc++.h>
using namespace std;
// Returns length of the longest substring
// with equal number of zeros and ones.
string stringLen(string str)
{
// Create a map to store differences
// between counts of 1s and 0s.
map<int, int> m;
// Initially difference is 0.
m[0] = -1;
int count_0 = 0, count_1 = 0;
int start, end, res = 0;
for (int i = 0; i < str.size(); i++) {
// Keeping track of counts of
// 0s and 1s.
if (str[i] == '0')
count_0++;
else
count_1++;
// If difference between current counts
// already exists, then substring between
// previous and current index has same
// no. of 0s and 1s. Update result if this
// substring is more than current result.
if (m.find(count_1 - count_0) != m.end()) {
if ((i - m[count_1 - count_0]) > res) {
start = m.find(
count_1 - count_0)
->second;
end = i;
res = end - start;
}
}
// If current difference
// is seen first time.
else
m[count_1 - count_0] = i;
}
if (count_0 == 0 || count_1 == 0)
return "-1";
// Return the substring
// between found indices
return str.substr(start + 1, end + 1);
}
// Driver Code
int main()
{
string str = "110101010";
cout << stringLen(str);
return 0;
}
Java
// Java code for the above approach
import java.io.*;
class GFG
{
// Returns length of the longest substring
// with equal number of zeros and ones.
static String stringLen(String str)
{
// Create a map to store differences
// between counts of 1s and 0s.
int [] m = new int[100000];
// Initially difference is 0.
m[0] = -1;
int count_0 = 0; int count_1 = 0;
int start = 0; int end = 0; int res = 0;
for (int i = 0; i < str.length(); i++) {
// Keeping track of counts of
// 0s and 1s.
if (str.charAt(i) == '0')
count_0++;
else
count_1++;
// If difference between current counts
// already exists, then substring between
// previous and current index has same
// no. of 0s and 1s. Update result if this
// substring is more than current result.
if (m[count_1 - count_0]!= 0) {
if ((i - m[count_1 - count_0]) > res) {
start = m[count_1 - count_0];
end = i;
res = end - start;
}
}
// If current difference
// is seen first time.
else
m[count_1 - count_0] = i;
}
if (count_0 == 0 || count_1 == 0)
return "-1";
// Return the substring
// between found indices
return str.substring(start , end + 2);
}
// Driver Code
public static void main (String[] args)
{
String str = "110101010";
System.out.println(stringLen(str));
}
}
// This code is contributed by Potta Lokesh
Python3
# Python for finding length
# of longest balanced substring
# Returns length of the longest substring
# with equal number of zeros and ones.
def stringLen (str) :
# Create a map to store differences
# between counts of 1s and 0s.
m = {}
# Initially difference is 0.
m[0] = -1
count_0 = 0
count_1 = 0
res = 0
for i in range(len(str)):
# Keeping track of counts of
# 0s and 1s.
if (str[i] == '0'):
count_0 += 1
else:
count_1 += 1
# If difference between current counts
# already exists, then substring between
# previous and current index has same
# no. of 0s and 1s. Update result if this
# substring is more than current result.
if ((count_1 - count_0) in m):
if ((i - m[count_1 - count_0]) > res):
start = m[(count_1 - count_0)]
end = i
res = end - start
# If current difference
# is seen first time.
else:
m[count_1 - count_0] = i
if (count_0 == 0 or count_1 == 0):
return "-1"
# Return the substring
# between found indices
return str[start + 1 : start + 1 + end + 1]
# Driver Code
str = "110101010"
print(stringLen(str))
# This code is contributed by Saurabh Jaiswal
C#
// C# code for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
// Returns length of the longest substring
// with equal number of zeros and ones.
static string stringLen(string str)
{
// Create a map to store differences
// between counts of 1s and 0s.
int []m = new int[100000];
// Initially difference is 0.
m[0] = -1;
int count_0 = 0; int count_1 = 0;
int start = 0; int end = 0; int res = 0;
for (int i = 0; i < str.Length; i++) {
// Keeping track of counts of
// 0s and 1s.
if (str[i] == '0')
count_0++;
else
count_1++;
// If difference between current counts
// already exists, then substring between
// previous and current index has same
// no. of 0s and 1s. Update result if this
// substring is more than current result.
if (m[count_1 - count_0]!= 0) {
if ((i - m[count_1 - count_0]) > res) {
start = m[count_1 - count_0];
end = i;
res = end - start;
}
}
// If current difference
// is seen first time.
else
m[count_1 - count_0] = i;
}
if (count_0 == 0 || count_1 == 0)
return "-1";
// Return the substring
// between found indices
return str.Substring(start, end - start + 2);
}
// Driver Code
public static void Main ()
{
string str = "110101010";
Console.Write(stringLen(str));
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript for finding length
// of longest balanced substring
// Returns length of the longest substring
// with equal number of zeros and ones.
const stringLen = (str) => {
// Create a map to store differences
// between counts of 1s and 0s.
let m = {};
// Initially difference is 0.
m[0] = -1;
let count_0 = 0, count_1 = 0;
let start, end, res = 0;
for (let i = 0; i < str.length; i++) {
// Keeping track of counts of
// 0s and 1s.
if (str[i] == '0')
count_0++;
else
count_1++;
// If difference between current counts
// already exists, then substring between
// previous and current index has same
// no. of 0s and 1s. Update result if this
// substring is more than current result.
if ((count_1 - count_0) in m) {
if ((i - m[count_1 - count_0]) > res) {
start = m[(count_1 - count_0)];
end = i;
res = end - start;
}
}
// If current difference
// is seen first time.
else
m[count_1 - count_0] = i;
}
if (count_0 == 0 || count_1 == 0)
return "-1";
// Return the substring
// between found indices
return str.substring(start + 1, start + 1 + end + 1);
}
// Driver Code
let str = "110101010";
document.write(stringLen(str));
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Generate all Binary Strings of length N with equal count of 0s and 1s Given an integer N, the task is to generate all the binary strings with equal 0s and 1s. If no strings are possible, print -1 Examples: Input: N = 2 Output: â01â, â10âExplanation: All possible binary strings of length 2 are: 01, 10, 11, 00. Out of these, only 2 have equal number of 0s and 1s Input:
6 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
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
Check if all substrings of length K of a Binary String has equal count of 0s and 1s Given a binary string S of length N and an even integer K, the task is to check if all substrings of length K contains an equal number of 0s and 1s. If found to be true, print âYesâ. Otherwise, print âNoâ. Examples: Input: S = "101010", K = 2Output: YesExplanation:Since all the substrings of length
6 min read
Count of all possible N length balanced Binary Strings Given a number N, the task is to find the total number of balanced binary strings possible of length N. A binary string is said to be balanced if: The number of 0s and 1s are equal in each binary stringThe count of 0s in any prefix of binary strings is always greater than or equal to the count of 1s
6 min read
Longest substring with count of 1s more than 0s Given a binary string find the longest substring which contains 1âs more than 0âs.Examples: Input : 1010Output : 3Substring 101 has 1 occurring more number of times than 0.Input : 101100Output : 5Substring 10110 has 1 occurring more number of times than 0.A simple solution is to one by one consider
8 min read
Longest Subsequence with equal 0s and 1s and all 0s before all 1s Given a binary string S, the task is to find the longest subsequence with that has equal number of 0s and 1s and all the 0s are present before all the 1s. Examples: Input: S = "0011001111"Output: 8Explanation: By removing the 3rd and 4th characters, the string becomes 00001111. This is the longest p
8 min read
Split the binary string into substrings with equal number of 0s and 1s 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
8 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