Length of the longest substring with equal 1s and 0s

Given a binary string. We need to find the length of longest balanced sub string. A sub string is balanced if it contains 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
```

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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. Time complexity of this would be O(n3)

An efficient solution is to use hashing.
1) Traverse string and keep track of counts of 1s and 0s as count_1 and count_0 respectively.
2) 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++

 `// CPP for finding length of longest balanced ` `// substring ` `#include ` `using` `namespace` `std; ` ` `  `// Returns length of the longest substring  ` `// with equal number of zeros and ones. ` `int` `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` `res = 0; ` `    ``for` `(``int` `i=0; i

Java

 `// Java Code for finding the length of ` `// the longest balanced substring  ` ` `  `import` `java.io.*; ` `import` `java.util.*; ` ` `  `public` `class` `MAX_LEN_0_1 { ` `    ``public` `static` `void` `main(String args[])``throws` `IOException ` `    ``{ ` `        ``String str = ``"101001000"``; ` `             `  `    ``// Create a map to store differences ` `    ``//between counts of 1s and 0s. ` `    ``HashMap map = ``new` `HashMap(); ` `     `  `    ``// Initially difference is 0; ` `            ``map. put(``0``, -``1``); ` `            ``int` `res =``0``; ` `            ``int` `count_0 = ``0``, count_1 = ``0``; ` `            ``for``(``int` `i=``0``; i

Python3

 `# Python3 code 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 python dictionary to store ` `    ``# differences between counts of 1s and 0s. ` `    ``m ``=` `dict``() ` `     `  `    ``# 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` `m.get(count_1 ``-` `count_0): ` `            ``res ``=` `max``(res, i ``-` `m[count_1 ``-` `count_0]) ` `         `  `        ``# If current difference is  ` `        ``# seen first time. ` `        ``else``: ` `            ``m[count_1 ``-` `count_0] ``=` `i ` `    ``return` `res ` ` `  `# driver code ` `str` `=` `"101001000"` `print``(``"Length of longest balanced"` `     ``" sub string = "``,stringLen(``str``)) ` ` `  `# This code is contributed by "Sharad_Bhardwaj" `

C#

 `// C# Code for finding the length of  ` `// the longest balanced substring  ` `using` `System; ` `using` `System.Collections.Generic; ` ` `  `class` `GFG ` `{ ` `public` `static` `void` `Main(``string``[] args) ` `{ ` `    ``string` `str = ``"101001000"``; ` ` `  `    ``// Create a map to store differences  ` `    ``//between counts of 1s and 0s.  ` `    ``Dictionary<``int``, ` `               ``int``> map = ``new` `Dictionary<``int``,  ` `                                         ``int``>(); ` `     `  `    ``// Initially difference is 0;  ` `    ``map[0] = -1; ` `    ``int` `res = 0; ` `    ``int` `count_0 = 0, count_1 = 0; ` `    ``for` `(``int` `i = 0; i < str.Length;i++) ` `    ``{ ` `        ``// Keep track of count 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` `(map.ContainsKey(count_1 - count_0)) ` `        ``{ ` `            ``res = Math.Max(res, (i - map[count_1 -  ` `                                         ``count_0])); ` `        ``} ` ` `  `        ``// If the current difference is ` `        ``// seen first time.  ` `        ``else` `        ``{ ` `            ``map[count_1 - count_0] = i; ` `        ``} ` ` `  `    ``} ` ` `  `    ``Console.WriteLine(``"Length of longest balanced"` `+  ` `                            ``" sub string = "` `+ res); ` `} ` `} ` ` `  `// This code is contributed by Shrikant13 `

Output:

```Length of longest balanced sub string = 6
```

Time Complexity: O(n)

Extended Problem : Largest subarray with equal number of 0s and 1s

This article is contributed by Shivam Pradhan (anuj_charm) and ASIPU PAWAN KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

4

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.