Show problems as
Classic problem #3900MediumHash TableStringPrefix Sum

Longest Balanced Substring After One Swap

Real-world version: Longest Even Stretch After One Swap
Tracked in this browser only
Read Longest Balanced Substring After One Swap on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A tape reads s, a string of '0' and '1'.

You may swap the characters at two positions of the tape, at most once. Swapping two equal characters is allowed and simply changes nothing.

A stretch of the tape is even when it holds as many '0' as '1'. Return the length of the longest even stretch the tape can be made to hold.

Examples

Example 1

Input
s = "01110"
Output
4

Left alone, the longest even stretch is just two characters. The four characters from position 1 to 4 hold three ones and one zero, two too many ones, and a zero sits outside them at the front, so swapping that zero in for one of the ones leaves that stretch even.

Example 2

Input
s = "1111"
Output
0

Every character is a one, so no swap changes anything and no stretch is ever even.

Example 3

Input
s = "0011"
Output
4

The whole tape is already even, so no swap is needed.

Constraints

  • 1 <= s.length <= 10^5
  • s[i] is either '0' or '1'

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def longest_balanced(s: str) -> int:
Java
public int longestBalanced(String s)