Trains the technique from
LeetCode 3900Longest Balanced Substring After One SwapThis 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.
Example 1
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
Every character is a one, so no swap changes anything and no stretch is ever even.
Example 3
The whole tape is already even, so no swap is needed.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def longest_balanced(s: str) -> int:public int longestBalanced(String s)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.