Problem · String

Longest Balanced Substring After One Swap

Learn this problem
MediumTekion logoTekionINTERNOA

Problem 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) → int

Examples

Example 1

s = "100001"return = 4

Swap 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 = 0

No non-empty balanced substring can be formed, so the maximum length is 0.

Constraints

  • 1 <= s.length <= 10^5.
  • s contains only '0' and '1'.

More Tekion problems

drafts saved locally
public int longestBalancedSubstringAfterOneSwap(String s) {
    // Write your code here.
}
s"100001"
expected4
checking account