Longest Balanced Substring After One Swap
Real-world version: Longest Even Stretch After One SwapThe 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.
def longest_balanced(s: str) -> int:public int longestBalanced(String s)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 20 test cases: 20 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Number of Wonderful SubstringsReal-world version: Nearly Even Telemetry StretchesMedium
- Unique Length-3 Palindromic SubsequencesReal-world version: Three-Letter Mirrored PicksMedium
- Find the Longest Substring Containing Vowels in Even CountsReal-world version: The Longest Stretch With Every Tally EvenMedium
- Number of Divisible SubstringsReal-world version: Stretches Whose Total Divides Their LengthMedium