Longest Balanced Substring II
Real-world version: The Longest Evenly Dyed StretchThe statement here is our own: the same inputs, outputs and technique.
A loom has laid down a run of dyed threads, threads spelling out the dye on each one as a, b or c.
A stretch of neighbouring threads is even when it holds as many a threads as b threads and as many b threads as c threads.
Return the number of threads in the longest even stretch, or 0 when no stretch of one thread or more is even.
Examples
Example 1
- Input
- threads = "abcabc"
- Output
- 6
Two of each dye across the whole run, so the whole run is even.
Example 2
- Input
- threads = "cabc"
- Output
- 3
The last three threads hold one of each dye. Taking the leading c as well would leave two c threads against one a thread.
Example 3
- Input
- threads = "aaabbbcc"
- Output
- 0
The run is three a threads, three b threads and two c threads. Any stretch reaching the c threads has already swallowed all three b threads, so no stretch ever balances and nothing qualifies.
Constraints
- 1 <= threads.length <= 10^5
- threads holds only the characters a, b and c
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(threads: str) -> int:public int longestBalanced(String threads)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 16 test cases: 16 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
- Longest Balanced Substring After One SwapReal-world version: Longest Even Stretch After One SwapMedium
- 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