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.
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)
Below is the implementation of the above approach:
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 email@example.com. 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.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- 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 that do not contain any palindrome
- Longest equal substring with cost less than K
- Length of the longest substring without repeating characters
- Length of the longest substring with no consecutive same letters
- Find length of longest substring with at most K normal characters
- Count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1's
- Longest palindrome formed by concatenating and reordering strings of equal length
- Find length of longest subsequence of one string which is substring of another string
- Minimum length of substring whose rotation generates a palindromic substring
- Construct a string of length L such that each substring of length X has exactly Y distinct letters
- Length of longest Palindromic Subsequence of even length with no two adjacent characters same
- Longest Palindromic Substring | Set 1