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 = 110101010
Output : Length of longest balanced sub string = 8
Input : input = 0000
Output : Length of longest balanced sub string = 0
A simple solution is to use two nested loops to generate every substring. And a third loop to count number of 0s and 1s in current substring.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isValid(string p)
{
int n = p.length();
int c1 = 0, c0 = 0;
for ( int i = 0; i < n; i++) {
if (p[i] == '0' )
c0++;
if (p[i] == '1' )
c1++;
}
return (c0 == c1) ? true : false ;
}
int longestSub(string s)
{
int max_len = 0;
int n = s.length();
for ( int i = 0; i < n; i++) {
for ( int j = i; j < n; j++) {
if (isValid(s.substr(i, j - i + 1)) && max_len < j - i + 1)
max_len = j - i + 1;
}
}
return max_len;
}
int main()
{
string s = "101001000" ;
cout << longestSub(s);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
public static boolean isValid(String p)
{
int n = p.length();
int c1 = 0 , c0 = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (p.charAt(i) == '0' )
{
c0++;
}
if (p.charAt(i) == '1' )
{
c1++;
}
}
if (c0 == c1)
{
return true ;
}
else
{
return false ;
}
}
public static int longestSub(String s)
{
int max_len = 0 ;
int n = s.length();
for ( int i = 0 ; i < n; i++)
{
for ( int j = i; j < n; j++)
{
if (isValid(s.substring(i, j + 1 )) && max_len < j - i + 1 )
{
max_len = j - i + 1 ;
}
}
}
return max_len;
}
public static void main (String[] args)
{
String s = "101001000" ;
System.out.println(longestSub(s));
}
}
|
Python3
def isValid(p):
n = len (p)
c1 = 0
c0 = 0
for i in range (n):
if (p[i] = = '0' ):
c0 + = 1
if (p[i] = = '1' ):
c1 + = 1
if (c0 = = c1):
return True
else :
return False
def longestSub(s):
max_len = 0
n = len (s)
for i in range (n):
for j in range (i, n):
if (isValid(s[i : j - i + 1 ]) and
max_len < j - i + 1 ):
max_len = j - i + 1
return max_len
if __name__ = = '__main__' :
s = "101001000"
print (longestSub(s))
|
C#
using System;
class GFG{
static bool isValid( string p)
{
int n = p.Length;
int c1 = 0, c0 = 0;
for ( int i = 0; i < n; i++)
{
if (p[i] == '0' )
{
c0++;
}
if (p[i] == '1' )
{
c1++;
}
}
if (c0 == c1)
{
return true ;
}
else
{
return false ;
}
}
public static int longestSub( string s)
{
int max_len = 0;
int n = s.Length;
for ( int i = 0; i < n; i++)
{
for ( int j = i; j < n; j++)
{
if (isValid(s.Substring(i, j - i + 1)) &&
max_len < j - i + 1)
{
max_len = j - i + 1;
}
}
}
return max_len;
}
static public void Main()
{
string s = "101001000" ;
Console.WriteLine(longestSub(s));
}
}
|
Javascript
<script>
function isValid(p)
{
var n = p.length;
var c1 = 0, c0 = 0;
for ( var i =0; i < n; i++)
{
if (p[i] == '0' )
c0++;
if (p[i] == '1' )
c1++;
}
return (c0 == c1) ? true : false ;
}
function longestSub(s)
{
var max_len = 0;
var n = s.length;
for ( var i = 0; i < n; i++)
{
for ( var j = i; j < n; j++)
{
if (isValid(s.substr(i, j - i + 1)) && max_len < j - i + 1)
max_len = j - i + 1;
}
}
return max_len;
}
var s = "101001000" ;
document.write( longestSub(s));
</script>
|
Time Complexity: O(N3)
Auxiliary Space: O(1)
An efficient solution is to use hashing.
- Traverse string and keep track of counts of 1s and 0s as count_1 and count_0 respectively.
- See if current difference between two counts has appeared before (We use hashing to store all differences and first index where a difference appears). If yes, then substring from previous appearance and current index has same number of 0s and 1s.
Below is the implementation of above approach.
C++
#include<bits/stdc++.h>
using namespace std;
int stringLen(string str)
{
map< int , int > m;
m[0] = -1;
int count_0 = 0, count_1 = 0;
int res = 0;
for ( int i=0; i<str.size(); i++)
{
if (str[i] == '0' )
count_0++;
else
count_1++;
if (m.find(count_1 - count_0) != m.end())
res = max(res, i - m[count_1 - count_0]);
else
m[count_1 - count_0] = i;
}
return res;
}
int main()
{
string str = "101001000" ;
cout << "Length of longest balanced"
" sub string = " ;
cout << stringLen(str);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class MAX_LEN_0_1 {
public static void main(String args[]) throws IOException
{
String str = "101001000" ;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
map. put( 0 , - 1 );
int res = 0 ;
int count_0 = 0 , count_1 = 0 ;
for ( int i= 0 ; i<str.length();i++)
{
if (str.charAt(i)== '0' )
count_0++;
else
count_1++;
if (map.containsKey(count_1-count_0))
res = Math.max(res, (i - map.get(count_1-count_0)));
else
map.put(count_1-count_0,i);
}
System.out.println( "Length of longest balanced sub string = " +res);
}
}
|
Python3
def stringLen( str ):
m = dict ()
m[ 0 ] = - 1
count_0 = 0
count_1 = 0
res = 0
for i in range ( len ( str )):
if str [i] = = '0' :
count_0 + = 1
else :
count_1 + = 1
if m.get(count_1 - count_0)! = None :
res = max (res, i - m[count_1 - count_0])
else :
m[count_1 - count_0] = i
return res
str = "101001000"
print ( "Length of longest balanced"
" sub string = " ,stringLen( str ))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static void Main( string [] args)
{
string str = "101001000" ;
Dictionary< int ,
int > map = new Dictionary< int ,
int >();
map[0] = -1;
int res = 0;
int count_0 = 0, count_1 = 0;
for ( int i = 0; i < str.Length;i++)
{
if (str[i] == '0' )
{
count_0++;
}
else
{
count_1++;
}
if (map.ContainsKey(count_1 - count_0))
{
res = Math.Max(res, (i - map[count_1 -
count_0]));
}
else
{
map[count_1 - count_0] = i;
}
}
Console.WriteLine( "Length of longest balanced" +
" sub string = " + res);
}
}
|
Javascript
<script>
let str = "101001000" ;
let map = new Map();
map.set(0, -1);
let res =0;
let count_0 = 0, count_1 = 0;
for (let i=0; i<str.length;i++)
{
if (str[i]== '0' )
count_0++;
else
count_1++;
if (map.has(count_1-count_0))
res =
Math.max(res, (i -
map.get(count_1-count_0)));
else
map.set(count_1-count_0,i);
}
document.write(
"Length of longest balanced sub string = " +res
);
</script>
|
Output
Length of longest balanced sub string = 6
Time Complexity: O(n)
Auxiliary Space: O(n)
Extended Problem: Largest subarray with equal number of 0s and 1s
Last Updated :
22 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...