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.
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(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.
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 firstname.lastname@example.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.
- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- Length of the longest substring that do not contain any palindrome
- Length of the longest valid substring
- Longest Even Length Substring such that Sum of First and Second Half is same
- Length of the longest substring without repeating characters
- Length of the longest substring with no consecutive same letters
- Count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1's
- Find length of longest subsequence of one string which is substring of another string
- Longest substring of vowels
- Longest substring with count of 1s more than 0s
- Longest Non-palindromic substring
- Longest Palindromic Substring | Set 2
- Longest Palindromic Substring | Set 1
- Longest Common Substring | DP-29
- Print the longest common substring