Leetcode 2609. Find the Longest Balanced Substring of a Binary String
You are given a binary string s
consisting only of the characters ‘0’ and ‘1’. A balanced binary string is defined as a binary string where 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 in the given binary string.
s
? (Typical constraint might be around 10^5)To solve the problem efficiently:
Here is the C++ implementation of the solution described above:
#include <iostream>
#include <unordered_map>
#include <string>
#include <algorithm>
int findLongestBalancedSubstring(const std::string& s) {
std::unordered_map<int, int> prefixSumMap;
int prefixSum = 0;
int maxLength = 0;
// Initialize the map with prefixSum value 0 at index -1
prefixSumMap[0] = -1;
for (int i = 0; i < s.size(); ++i) {
// Update the prefix sum
if (s[i] == '0') {
prefixSum++;
} else {
prefixSum--;
}
// Check if this prefix sum has been seen before
if (prefixSumMap.find(prefixSum) != prefixSumMap.end()) {
// Calculate the length of the balanced substring
int length = i - prefixSumMap[prefixSum];
maxLength = std::max(maxLength, length);
} else {
// Store the first occurrence of this prefix sum
prefixSumMap[prefixSum] = i;
}
}
return maxLength;
}
int main() {
std::string s = "00110011";
std::cout << "The length of the longest balanced substring is: " << findLongestBalancedSubstring(s) << std::endl;
return 0;
}
The time complexity of the solution is O(n), where n is the length of the string s
. This is because we are iterating through the string once and performing constant time operations (hash map insertions and lookups) for each character. The space complexity is O(n) due to the hash map storing prefix sums and their respective indices.
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?