All problems
1194MediumHash TableStringPrefix Sum

The Longest Evenly Dyed Stretch

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3714Longest Balanced Substring II

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 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 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(threads: str) -> int:
Java
public int longestBalanced(String threads)
September 7
Apply