All problems
0934MediumHash TableStringPrefix Sum

Longest Even Stretch After One Swap

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3900Longest Balanced Substring After One Swap

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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