Longest Valid Parentheses
Real-world version: Longest Clean Trace WindowThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def longest_clean_window(trace: str) -> int:public int longestCleanWindow(String trace)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 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
- Valid Parenthesis StringReal-world version: Salvage a Smudged Span TraceMedium
- Remove Outermost ParenthesesReal-world version: Strip Root Frame MarkersEasy
- Maximum Nesting Depth of the ParenthesesReal-world version: Deepest Bracket LayerEasy
- Generate ParenthesesReal-world version: Ridge Walk PlansMedium