You are given a binary string s consisting only of characters '0' and '1'.
A string is balanced if it contains an equal number of '0's and '1's.
You can perform at most one swap between any two characters in s. Then, you select a balanced substring from s.
Return an integer representing the maximum length of the balanced substring you can select.
Example 1:
Input: s = "100001"
Output: 4
Explanation:
"100001". The string becomes "101000"."101000", which is balanced because it has two '0's and two '1's.Example 2:
Input: s = "111"
Output: 0
Explanation:
'0's and zero '1's.Constraints:
1 <= s.length <= 105s consists only of the characters '0' and '1'.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The problem asks for the maximum length of a balanced substring achievable after at most one swap of characters. A substring can be balanced without any swap if it already has equal counts of zeros and ones. Alternatively, a substring with an imbalance of two can be balanced by swapping one excess character with a needed character from outside the substring.
Here's how the algorithm would work step-by-step:
def longest_balanced_substring(s: str) -> int:
total_zeros = s.count('0')
total_ones = len(s) - total_zeros
# Track the earliest index where each balance difference was observed
earliest_seen = {}
earliest_seen[0] = -1
current_balance = 0
max_length = 0
# Process the binary string and evaluate potential balanced windows
for current_index, character in enumerate(s):
current_balance += 1 if character == '1' else -1
if current_balance in earliest_seen:
window_length = current_index - earliest_seen[current_balance]
if window_length > max_length:
max_length = window_length
else:
earliest_seen[current_balance] = current_index
# Check if swapping a character from outside can balance a difference of 2
for balance_diff in (-2, 2):
target_balance = current_balance - balance_diff
if target_balance in earliest_seen:
window_length = current_index - earliest_seen[target_balance]
window_ones = (window_length + balance_diff) // 2
window_zeros = window_length - window_ones
if balance_diff == 2 and total_zeros > window_zeros:
if window_length > max_length:
max_length = window_length
elif balance_diff == -2 and total_ones > window_ones:
if window_length > max_length:
max_length = window_length
return max_length
Treat each one as plus one and each zero as minus one. A stretch is already balanced when the running total returns to a value seen before. One swap can also repair a stretch that is off by exactly two, if the character you need still exists outside that stretch. Remembering where each running total first appeared finds the longest stretch in one pass.
Here's how the algorithm would work step-by-step:
def longest_balanced(s):
zero_count = s.count("0")
one_count = len(s) - zero_count
positions = {0: [-1]}
best_length = 0
balance = 0
for index, character in enumerate(s):
balance += 1 if character == "1" else -1
positions.setdefault(balance, []).append(index)
best_length = max(best_length, index - positions[balance][0])
for offset, outside_count in ((-2, zero_count), (2, one_count)):
earlier = positions.get(balance + offset)
if earlier is None:
continue
length_from_first = index - earlier[0]
minority_inside = (length_from_first - 2) // 2
if minority_inside < outside_count:
best_length = max(best_length, length_from_first)
elif len(earlier) > 1:
best_length = max(best_length, index - earlier[1])
return best_length
| Case | How to Handle |
|---|---|
| Empty string or string with a single parenthesis | Return zero immediately since a valid balanced substring requires at least two characters. |
| String already completely balanced without any swaps | The algorithm must correctly compute the full length of the string and allow a zero-effect swap if necessary. |
| String containing an odd number of parentheses | Ensure the logic naturally caps the maximum possible balanced substring length to an even number. |
| String with an unequal count of opening and closing parentheses | Pre-counting total parentheses allows the algorithm to determine if a global fix via a single swap is even mathematically possible. |
| Extremely long strings reaching maximum constraint limits | An optimized linear or sub-quadratic approach must be used to avoid time limit exceeded errors in FAANG interviews. |
| Strings consisting entirely of opening or entirely of closing brackets | The solution must gracefully handle the scenario where no valid balanced substring greater than two can be formed. |
| Swapping characters outside the target substring to fix it | Ensure the swap logic strictly applies within or directly contributes to the contiguous window being evaluated. |