Valid Parenthesis String
Real-world version: Salvage a Smudged Span TraceThe statement here is our own: the same inputs, outputs and technique.
A packaging tool records a trace while it walks a project. It writes ( when it enters a span and ) when it leaves one, and a leaving mark always settles the span that was entered most recently and is still open. A trace is sound when every leaving mark settles some earlier entering mark and no span is left open once the trace runs out.
One run wrote to a failing disk, so a few bytes came back smudged. A smudged byte is recorded as *, and each one may have held an entering mark, a leaving mark, or no mark at all. Two smudged bytes need not be read the same way.
You are handed the recovered trace s. Return true when at least one reading of the smudged bytes leaves a sound trace, and false when no reading does.
Examples
Example 1
- Input
- s = "((**))"
- Output
- true
Read both smudged bytes as carrying no mark and the trace becomes two entering marks followed by two leaving marks, which is sound.
Example 2
- Input
- s = "*)(("
- Output
- false
The trace finishes with two entering marks and nothing after them, so two spans stay open no matter how the leading smudge is read.
Example 3
- Input
- s = "**"
- Output
- true
Reading both bytes as carrying no mark leaves an empty trace, which is sound; reading the first as entering and the second as leaving works too.
Constraints
- 1 <= s.length <= 100
- Every character of `s` is `(`, `)` 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 trace_is_recoverable(s: str) -> bool:public boolean traceIsRecoverable(String s)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 18 test cases: 18 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
- Minimum Number of Swaps to Make the String BalancedReal-world version: Balance the Clamp TapeMedium
- Minimum Add to Make Parentheses ValidReal-world version: Repairing the Bracket LogMedium
- Check if a Parentheses String Can Be ValidReal-world version: Can the Bracket Tape Be BalancedMedium
- Longest Valid ParenthesesReal-world version: Longest Clean Trace WindowHard