Longest Balanced Substring After One Swap - Solution & Explanation
Problem Statement
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:
- Swap
"100001". The string becomes"101000". - Select the substring
"101000", which is balanced because it has two'0's and two'1's.
Example 2:
Input: s = "111"
Output: 0
Explanation:
- Choose not to perform any swaps.
- Select the empty substring, which is balanced because it has zero
'0's and zero'1's.
Constraints:
1 <= s.length <= 105sconsists only of the characters'0'and'1'.
Approach Overview
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.
Solution
Let the prefix sum pre denote the number of 1s minus the number of 0s in the current prefix. Then for any substring, if the numbers of 0s and 1s are equal, its corresponding prefix sum difference is 0.
Therefore, if the prefix sum at position i is x, and some previous position also has prefix sum x, then the substring between these two positions is balanced, and we can directly use it to update the answer.
Now the problem allows us to perform at most one swap between any two characters. One swap can only reduce the difference between the counts of 1 and 0 in a substring by 2. So besides the case where the prefix sum difference is 0, we also need to consider:
- A prefix sum difference of
2, which means the substring contains 2 more1s than0s. In this case, if there is still at least one0outside the substring, we can make it balanced with one swap. - A prefix sum difference of
-2, which means the substring contains 2 more0s than1s. Similarly, if there is still at least one1outside the substring, we can make it balanced with one swap.
To do this, we first count the total numbers of 0s and 1s in the whole string, denoted by cnt0 and cnt1. Then we use a hash table to record all positions where each prefix sum appears.
While traversing the string up to position i, let the current prefix sum be pre:
- Use the earliest occurrence of
preto update the longest balanced substring length without any swap. - If prefix sum
pre - 2exists, then we can try to form a substring with 2 more1s than0s. Suppose its length isL. Then the number of0s inside it is(L - 2) / 2. Only when this value is strictly less thancnt0do we know there is at least one0outside the substring that can be swapped in. - If prefix sum
pre + 2exists, we can similarly try to form a substring with 2 more0s than1s. In this case, we need the number of1s inside it to be strictly less thancnt1.
Since an earlier occurrence of the same prefix sum gives a longer substring, we always try the earliest position first. If it cannot satisfy the condition that there is still a character outside the substring available for swapping, we try the second earliest position.
The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the string s.
Code
Python
Java
C++
Go
TypeScript
Detailed Complexity Analysis
| 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 |
Video Solution
Leetcode 3900 | Longest Balanced Substring After One Swap | Leetcode weekly contest 497 • CodeWithMeGuys • 2,063 views views
Watch 5 more video solutions →Frequently Asked Questions
Is Longest Balanced Substring After One Swap easy or hard?
Longest Balanced Substring After One Swap Python/Java solution
How to solve Longest Balanced Substring After One Swap in O(n)?
What is the best approach for Longest Balanced Substring After One Swap?
Is Longest Balanced Substring After One Swap asked at Google/Amazon/Meta?
What data structure is used in Longest Balanced Substring After One Swap?
What is the time complexity of Longest Balanced Substring After One Swap?
Ready to solve this problem?
Practice Longest Balanced Substring After One Swap with our built-in code editor and test cases.
Practice on FleetCode