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.
// CPP for finding length of longest balanced
// Returns length of the longest substring
// with equal number of zeros and ones.
// Create a map to store differences
// between counts of 1s and 0s.
// Initially difference is 0.
m = -1;
count_0 = 0, count_1 = 0;
res = 0;
i=0; i<str.size(); i++)
// Keeping track of counts of
// 0s and 1s.
// 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.
(m.find(count_1 - count_0) != m.end())
res = max(res, i - m[count_1 - count_0]);
// If current difference is seen first time.
m[count_1 - count_0] = i;
// driver function
string str =
"Length of longest balanced"
" sub string = "
cout << stringLen(str);
Length of longest balanced sub string = 6
Time Complexity : O(n)
Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at
http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements