Longest Balanced Substring After One Swap solution and explanation
5 more videos on this problem
Leetcode 3900 | Longest Balanced Substring After One Swap | Leetcode weekly contest 497CodeWithMeGuys · 20:57 · 2K views
weekly contest 497 | leetcode 3898 | leetcode 3899 | leetcode 3900 | leetcode 3901 | DSACode With Vick · 51:21 · 1K views
Longest Balanced Substring After One Swap | Leetcode 3900Techdose · 52:41 · 1K views
LeetCode 3900 | Longest Balanced Substring After One Swap | LeetCode contest | Contest 497 | Q3AlgoTribe · 21:16 · 734 views
3900. Longest Balanced Substring After One Swap LEETCODE WEEKLY 497 EASIEST APPROACH EVERBEASTCODES · 36:12 · 390 views
3900. Longest Balanced Substring After One Swap (Leetcode Medium)Programming Live with Larry · 22:03 · 95 views
The problem
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.
class Solution:
def longestBalanced(self, s: str) -> int:
cnt0 = s.count("0")
cnt1 = len(s) - cnt0
pos = {0: [-1]}
ans = pre = 0
for i, c in enumerate(s):
pre += 1 if c == "1" else -1
pos.setdefault(pre, []).append(i)
ans = max(ans, i - pos[pre][0])
if pre - 2 in pos:
p = pos[pre - 2]
if (i - p[0] - 2) // 2 < cnt0:
ans = max(ans, i - p[0])
elif len(p) > 1:
ans = max(ans, i - p[1])
if pre + 2 in pos:
p = pos[pre + 2]
if (i - p[0] - 2) // 2 < cnt1:
ans = max(ans, i - p[0])
elif len(p) > 1:
ans = max(ans, i - p[1])
return ansclass Solution {
public int longestBalanced(String s) {
int cnt0 = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '0') {
++cnt0;
}
}
int cnt1 = s.length() - cnt0;
Map<Integer, List<Integer>> pos = new HashMap<>();
pos.put(0, new ArrayList<>(List.of(-1)));
int ans = 0;
int pre = 0;
for (int i = 0; i < s.length(); ++i) {
pre += s.charAt(i) == '1' ? 1 : -1;
pos.computeIfAbsent(pre, k -> new ArrayList<>()).add(i);
ans = Math.max(ans, i - pos.get(pre).get(0));
if (pos.containsKey(pre - 2)) {
List<Integer> p = pos.get(pre - 2);
if ((i - p.get(0) - 2) / 2 < cnt0) {
ans = Math.max(ans, i - p.get(0));
} else if (p.size() > 1) {
ans = Math.max(ans, i - p.get(1));
}
}
if (pos.containsKey(pre + 2)) {
List<Integer> p = pos.get(pre + 2);
if ((i - p.get(0) - 2) / 2 < cnt1) {
ans = Math.max(ans, i - p.get(0));
} else if (p.size() > 1) {
ans = Math.max(ans, i - p.get(1));
}
}
}
return ans;
}
}class Solution {
public:
int longestBalanced(string s) {
int cnt0 = count(s.begin(), s.end(), '0');
int cnt1 = s.size() - cnt0;
unordered_map<int, vector<int>> pos;
pos[0] = {-1};
int ans = 0, pre = 0;
for (int i = 0; i < s.size(); ++i) {
pre += s[i] == '1' ? 1 : -1;
pos[pre].push_back(i);
ans = max(ans, i - pos[pre][0]);
if (pos.contains(pre - 2)) {
auto& p = pos[pre - 2];
if ((i - p[0] - 2) / 2 < cnt0) {
ans = max(ans, i - p[0]);
} else if (p.size() > 1) {
ans = max(ans, i - p[1]);
}
}
if (pos.contains(pre + 2)) {
auto& p = pos[pre + 2];
if ((i - p[0] - 2) / 2 < cnt1) {
ans = max(ans, i - p[0]);
} else if (p.size() > 1) {
ans = max(ans, i - p[1]);
}
}
}
return ans;
}
};function longestBalanced(s: string): number {
const cnt0 = [...s].filter(c => c === '0').length;
const cnt1 = s.length - cnt0;
const pos = new Map<number, number[]>();
pos.set(0, [-1]);
let ans = 0;
let pre = 0;
for (let i = 0; i < s.length; ++i) {
pre += s[i] === '1' ? 1 : -1;
if (!pos.has(pre)) {
pos.set(pre, []);
}
pos.get(pre)!.push(i);
ans = Math.max(ans, i - pos.get(pre)![0]);
if (pos.has(pre - 2)) {
const p = pos.get(pre - 2)!;
if ((i - p[0] - 2) >> 1 < cnt0) {
ans = Math.max(ans, i - p[0]);
} else if (p.length > 1) {
ans = Math.max(ans, i - p[1]);
}
}
if (pos.has(pre + 2)) {
const p = pos.get(pre + 2)!;
if ((i - p[0] - 2) >> 1 < cnt1) {
ans = Math.max(ans, i - p[0]);
} else if (p.length > 1) {
ans = Math.max(ans, i - p[1]);
}
}
}
return ans;
}func longestBalanced(s string) int {
cnt0 := strings.Count(s, "0")
cnt1 := len(s) - cnt0
pos := map[int][]int{0: {-1}}
ans, pre := 0, 0
for i, c := range s {
if c == '1' {
pre++
} else {
pre--
}
pos[pre] = append(pos[pre], i)
ans = max(ans, i-pos[pre][0])
if p, ok := pos[pre-2]; ok {
if (i-p[0]-2)/2 < cnt0 {
ans = max(ans, i-p[0])
} else if len(p) > 1 {
ans = max(ans, i-p[1])
}
}
if p, ok := pos[pre+2]; ok {
if (i-p[0]-2)/2 < cnt1 {
ans = max(ans, i-p[0])
} else if len(p) > 1 {
ans = max(ans, i-p[1])
}
}
}
return ans
}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 |
Frequently asked questions
Is Longest Balanced Substring After One Swap easy or hard?
The problem is rated Medium because the brute force idea is straightforward but the optimal solution requires reasoning about imbalance positions and how a single swap affects substring validity. Recognizing the greedy linear scan is the key insight.
Longest Balanced Substring After One Swap Python/Java solution
Python, Java, and C++ implementations typically follow the same idea: iterate through the string, track balance counts, detect invalid segments, and compute the maximum length achievable after correcting one imbalance with a swap. The final solution runs in O(n) time.
How to solve Longest Balanced Substring After One Swap in O(n)?
Perform a single pass through the string while maintaining a balance counter and tracking invalid boundaries. Identify segments where one misplaced character causes imbalance. A single swap can fix one such segment, allowing two valid regions to merge into a longer balanced substring.
What is the best approach for Longest Balanced Substring After One Swap?
The optimal method uses a greedy scan with prefix balance tracking. By analyzing where the string becomes imbalanced and how a single swap can fix one mismatch block, you can compute the maximum achievable balanced substring in O(n) time and O(1) space.
Is Longest Balanced Substring After One Swap asked at Google/Amazon/Meta?
Problems involving longest valid substrings, balance counters, and single modification operations appear frequently in interviews at companies like Google, Amazon, and Meta. Variants of longest valid parentheses and substring correction are common string algorithm questions.
What data structure is used in Longest Balanced Substring After One Swap?
The solution mainly uses counters and prefix balance tracking rather than complex data structures. Some implementations also rely on stack logic similar to longest valid parentheses problems or prefix arrays for faster imbalance detection.
What is the time complexity of Longest Balanced Substring After One Swap?
The optimal solution runs in O(n) time with O(1) extra space using a single linear scan and balance counters. Brute force approaches that try every swap pair take O(n^3), while improved simulations with prefix balance checks reduce it to about O(n^2).
