Longest Balanced Substring After One Swap

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
Inputs = "100001"
Output4
After swapping the indicated 0 and 1, the string becomes 101000, and the substring 1010 is balanced with two 0s and two 1s.
Example 2
Inputs = "111"
Output0
With no swap, the empty substring is balanced because it has zero 0s and zero 1s.

Constraints

  • 1 <= s.length <= 10^5
  • s consists only of the characters '0' and '1'.

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate