You are given a binary string 'S' of length 'N'. Your task is to find the length of the longest substring with an equal number of 1s and 0s.
Note:
1. The given string will only contain 0 and 1.
The first line contains an integer, βT,β which denotes the number of test cases or queries to be run. Then, the 'T' test cases follow.
The first line of each test case contains one integer 'N', as described in the problem statement.
The second line of each test case contains one binary string of length 'N'.
Output Format:
For each test case, return an integer representing the length of the longest substring with the equal number of 1s and 0s.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= N <= 5 * 10^3
It is guaranteed that S will only contain '0' and '1'.
Time Limit: 1 second
1
5
01100
4
The output is 4 because the substring from index 1 to 4(we are considering 0-based indexing) contains equal numbers of 0s and 1s and its length is 4.
1
6
111111
0
Since we can not find any substring having equal numbers of 0s and 1s, therefore the answer is 0.
Try to iterate on each substring one by one.
In this brute force approach, we will check each substring one by one and check if the current substring has equal numbers of 0s and 1s. If it is true, then we will update our answer with the length of this substring if the length of the current substring is larger than our previous answer.
Steps:
O(N^3), where βNβ is the length of the given string.
We are iterating on each substring of the given string. Since the number of substrings in a string is in the order of N^2 and finally we iterate on the selected substring, therefore the time complexity is in the order of O(N^3).
O(1).
Since constant extra space is required.