All problems
0087HardStringDynamic ProgrammingStackBracket Sequences

Longest Clean Trace Window

Tracked in this browser only
Write code

Trains the technique from

LeetCode 32Longest Valid Parentheses

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 profiler writes one character into trace per event it sees: ( when a span opens and ) when a span closes. No other character is written, and a run with no events at all leaves trace empty.

A window is a stretch of neighbouring characters of trace. A window is clean when its opens and closes pair off completely inside it: every ) in the window is answered by an unused ( sitting earlier in the same window, and no ( in the window is left waiting when the window ends.

Return the length of the longest clean window. When no window of one character or more is clean, return 0.

Examples

Example 1

Input
trace = "))(())()"
Output
6

Dropping the two stray closes at the front leaves the last six characters, which pair off completely.

Example 2

Input
trace = "()(()"
Output
2

The first two characters pair off, and so do the last two, but no clean window reaches past the open at position 2.

Example 3

Input
trace = "(("
Output
0

Both spans are still waiting when the trace ends, so nothing pairs off.

Constraints

  • 0 <= trace.length <= 3 * 10^4
  • Every character of trace is either '(' or ')'

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_clean_window(trace: str) -> int:
Java
public int longestCleanWindow(String trace)
September 7
Apply