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'.Problem Overview: Given a string containing characters that must form a balanced pattern (commonly parentheses or symmetric pairs), you may swap two characters at most once. The goal is to maximize the length of a substring that becomes balanced after that swap.
Approach 1: Brute Force Swap Simulation (O(n^3) time, O(1) space)
Try every possible pair of indices (i, j) and perform a swap. After each swap, scan the entire string and compute the longest balanced substring using a simple balance counter. For parentheses-style balance, increment on '(' and decrement on ')'; reset when the balance becomes negative. This approach proves correctness and helps reason about the effect of swaps, but the triple nested work (swap → scan → substring check) makes it impractical for large inputs.
Approach 2: Prefix Balance + Longest Valid Scan (O(n^2) time, O(n) space)
Precompute prefix balances so you can quickly evaluate whether a substring can be balanced. For each candidate swap, update the affected prefix difference and recompute the longest valid segment using the classic longest valid parentheses scan. The key observation: a swap only changes local balance transitions. By limiting recomputation to segments around the swapped indices, the algorithm avoids scanning the full string repeatedly. This still requires checking O(n^2) swap pairs but reduces validation cost significantly.
Approach 3: Greedy Balance Correction (O(n) time, O(1) space)
The optimal strategy relies on analyzing imbalance positions. Scan the string while tracking open/close counts and the maximum valid segment length. When an imbalance appears (too many closing characters), mark the boundary where a swap could fix it. A single swap can correct one major imbalance block, effectively merging two valid regions into a longer balanced substring. By tracking prefix balance and counting how many misplaced characters exist, you can compute the maximum achievable balanced window without explicitly performing swaps.
This technique behaves like a specialized two pointers or greedy window scan combined with prefix balance tracking. The algorithm processes the string once, updating counters and candidate segment lengths dynamically.
Recommended for interviews: The greedy O(n) scan with prefix balance reasoning is what interviewers typically expect. Explaining the brute force swap simulation first demonstrates understanding of the swap effect, but the optimized linear scan shows strong command of string algorithms and imbalance correction techniques.
Solutions for this problem are being prepared.
Try solving it yourself| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Swap Simulation | O(n^3) | O(1) | Understanding the effect of swaps or validating small inputs |
| Prefix Balance + Revalidation | O(n^2) | O(n) | Moderate input sizes where swap candidates must be evaluated |
| Greedy Balance Correction | O(n) | O(1) | Interview-ready optimal solution for large strings |
Practice Longest Balanced Substring After One Swap with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor