Longest Balanced Substring After One Swap Problem
Description
LeetCode Problem 3900.
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 <= 10^5sconsists only of the characters'0'and'1'.
Solution
Approach: Prefix Sum + Hash Table
Let pre be the number of 1s minus the number of 0s in the current prefix. A substring is balanced exactly when the prefix values at its two ends are equal.
One swap changes the difference #1 - #0 of a substring by exactly 2, and only if the swapped character comes from outside the substring. So besides balanced substrings we can also use:
- A substring with two more
1s than0s, provided some0lies outside it (swap an inside1with that0). - A substring with two more
0s than1s, provided some1lies outside it.
Count the zeros cnt0 and ones cnt1 of the whole string, and record, for every prefix value, the list of positions where it occurs (starting with -1 for value 0). While scanning position i with prefix pre:
- The earliest position with the same
pregives the longest balanced substring ending ati. - The earliest position with
pre - 2gives a substring of lengthLwith two more1s than0s, so it holds(L - 2) / 2zeros. It is usable if that is less thancnt0. If it holds all the zeros, take the second earliest position instead: the part between the two positions is balanced and non-empty, so the shorter substring has fewer zeros and works. - Symmetrically for
pre + 2, usingcnt1.
Complexity:
- Time complexity:
O(n). - Space complexity:
O(n).
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 ans