You’re given a binary string ( s ) (a string consisting only of the characters ‘0’ and ‘1’). A binary string is considered balanced if the number of ‘0’s is equal to the number of ‘1’s. Your task is to find the length of the longest balanced substring within the given string ( s ).
Consider the binary string s = "00111011"
.
This approach uses the concept of prefix sum to track balances and exploit the properties of balanced segments.
def find_the_longest_balanced_substring(s: str) -> int:
balance = 0
balance_map = {0: -1}
max_length = 0
for i, char in enumerate(s):
if char == '1':
balance += 1
else:
balance -= 1
if balance in balance_map:
max_length = max(max_length, i - balance_map[balance])
else:
balance_map[balance] = i
return max_length
# Example usage
print(find_the_longest_balanced_substring("00111011")) # Output: 4
The algorithm ensures we efficiently find the longest balanced substring by leveraging the properties of balanced prefixes and their occurrences.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?