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. Time complexity of this would be O(n^{3})

Below is the implementation of the above approach:

## C++

`// C++ program to find the length of ` `// the longest balanced substring ` `#include<bits/stdc++.h> ` `using` `namespace` `std; ` ` ` `// Function to check if a string contains ` `// equal number of one and zeros or not ` `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` `; ` `} ` ` ` `// Function to find the length of ` `// the longest balanced substring ` `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; ` ` ` `} ` ` ` `// Driver code ` `int` `main() ` `{ ` ` ` `string s = ` `"101001000"` `; ` ` ` ` ` `// Function call ` ` ` `cout << longestSub(s); ` ` ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

## Python3

`# Python3 program to find the length of ` `# the longest balanced substring ` ` ` `# Function to check if a contains ` `# equal number of one and zeros or not ` `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` ` ` `# Function to find the length of ` `# the longest balanced substring ` `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 ` ` ` `# Driver code ` `if` `__name__ ` `=` `=` `'__main__'` `: ` ` ` ` ` `s ` `=` `"101001000"` ` ` ` ` `# Function call ` ` ` `print` `(longestSub(s)) ` ` ` `# This code is contributed by mohit kumar 29 ` |

*chevron_right*

*filter_none*

**Output:**

6

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++

`// 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. ` `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<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()) ` ` ` `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 function ` `int` `main() ` `{ ` ` ` `string str = ` `"101001000"` `; ` ` ` `cout << ` `"Length of longest balanced"` ` ` `" sub string = "` `; ` ` ` `cout << stringLen(str); ` ` ` `return` `0; ` `}` |

*chevron_right*

*filter_none*

## 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<Integer,Integer> map = ` `new` `HashMap<Integer,Integer>(); ` ` ` ` ` `// Initially difference is 0; ` ` ` `map. put(` `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.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` `(map.containsKey(count_1-count_0)) ` ` ` `res = Math.max(res, (i - map.get(count_1-count_0))); ` ` ` ` ` `// If the current difference is seen first time. ` ` ` `else` ` ` `map.put(count_1-count_0,i); ` ` ` ` ` `} ` ` ` ` ` `System.out.println(` `"Length of longest balanced sub string = "` `+res); ` ` ` `} ` `} ` |

*chevron_right*

*filter_none*

## 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" ` |

*chevron_right*

*filter_none*

## 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 ` |

*chevron_right*

*filter_none*

**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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- Length of longest substring to be deleted to make a string equal to another string
- Check whether two strings can be made equal by reversing substring of equal length from both strings
- Minimum length of substring whose rotation generates a palindromic substring
- Longest Even Length Substring such that Sum of First and Second Half is same
- Longest Substring having equal count of Vowels and Consonants
- Count of binary strings of length N having equal count of 0's and 1's and count of 1's ≥ count of 0's in each prefix substring
- Length of the longest substring without repeating characters
- Find length of longest subsequence of one string which is substring of another string
- Length of the longest substring that do not contain any palindrome
- Length of the longest substring with no consecutive same letters
- Length of longest substring having all characters as K
- Find length of longest substring with at most K normal characters
- Length of Longest Palindrome Substring
- Length of the longest valid substring
- Length of the longest substring with every character appearing even number of times
- Longest equal substring with cost less than K
- Construct a string of length L such that each substring of length X has exactly Y distinct letters
- Count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1's
- Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'th substring