Problem · String
Longest Balanced Substring After One Swap
Learn this problemProblem statement
You are given a binary string s consisting only of '0' and '1'.
A string is balanced when it contains an equal number of '0' and '1' characters.
You may swap any two characters in s at most once. After the optional swap, select a balanced substring of s.
Return the maximum possible length of the selected balanced substring.
Function
longestBalancedSubstringAfterOneSwap(s: String) → intExamples
Example 1
s = "100001"return = 4Swap the third character with the final character to obtain 101000. Its prefix 1010 is balanced, with two zeroes and two ones.
Example 2
s = "111"return = 0No non-empty balanced substring can be formed, so the maximum length is 0.
Constraints
1 <= s.length <= 10^5.scontains only'0'and'1'.