Longest balanced binary substring with equal count of 1s and 0s
Given a binary string str of size N. The task is to find the longest balanced substring. A substring is balanced if it contains an equal number of 0 and 1.
Input: str = “110101010”
Explanation: The formed substring contain equal count of 1 and 0 i.e, count of 1 and 0 is same equal to 4.
Input: str = “0000”
Naive Approach: A simple solution is to use two nested loops to generate every substring. And a third loop to count a number of 0s and 1s in the current substring. Then print the longest substring among them.
Time Complexity: O(N^3)
Auxiliary Space: O(1)
Efficient solution: With the help of precomputation, store the difference between the count of 0s and the count of 1s from start till current index. This difference can then be used to determine the longest substring with equal 0s and 1s, as the longest distance between any duplicate values in the difference array. Use a Map-based hashing to do precomputation. Follow the steps below to solve the problem:
- Initialize the map<int, int> m.
- Set the value of m as -1.
- Initialize the variables count_0, count_1, res, start and end.
- Traverse the string str using the variable i and perform the following tasks:
- Keep the track of counts of 1s and 0s as count_1 and count_0 respectively.
- See if the current difference between count_1 and count_0 is already there in the map m or not. If yes, then perform the following tasks:
- The substring from the previous appearance and current index has same number of 0s and 1s.
- If the current found substring’s length is greater than res then set the found substring as the answer so far.
- If it is appearing for the first time, store the current difference and the current index in the map i.e, m[count_1 – count_0] equals i.
- If count_0 and count_1 are both 0, then print -1.
- Otherwise, print the substring from start to end.
Below is the implementation of the above approach.
Time Complexity: O(N)
Auxiliary Space: O(N)
Please Login to comment...