Trains the technique from
LeetCode 3714Longest Balanced Substring IIThis 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 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.
Example 1
Two of each dye across the whole run, so the whole run is even.
Example 2
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
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.
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(threads: str) -> int:public int longestBalanced(String threads)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.