Check if a Parentheses String Can Be Valid
Real-world version: Can the Bracket Tape Be BalancedThe statement here is our own: the same inputs, outputs and technique.
A tape of brackets reads tape, each character either '(' or ')'. A second string fixed of the same length says which of them are settled: a '1' means that bracket cannot be altered, and a '0' means it may be replaced by either bracket.
A tape is balanced when its brackets pair off one to one, each opening bracket with a closing bracket somewhere after it, and no pairs crossing.
Return whether some choice for the alterable places leaves the tape balanced.
Examples
Example 1
- Input
- tape = "))((", fixed = "0110"
- Output
- true
The two ends are alterable and the two middle brackets are settled. Making the first place an opening and the last a closing gives a tape whose brackets pair off as two neighbouring couples.
Example 2
- Input
- tape = ")(", fixed = "11"
- Output
- false
Both brackets are settled the wrong way round, and nothing may be altered, so the closing bracket at the front has nothing before it to match.
Example 3
- Input
- tape = "(())", fixed = "1111"
- Output
- true
Every bracket is settled and the tape already pairs off, one couple inside the other.
Constraints
- 1 <= tape.length <= 10^5
- fixed.length == tape.length
- Every character of tape is a round bracket, opening or closing.
- Every character of fixed is '0' or '1'.
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 can_be_valid(tape: str, fixed: str) -> bool:public boolean canBeValid(String tape, String fixed)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
- Valid Parenthesis StringReal-world version: Salvage a Smudged Span TraceMedium
- 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
- Remove Outermost ParenthesesReal-world version: Strip Root Frame MarkersEasy