Minimum Add to Make Parentheses Valid
Real-world version: Repairing the Bracket LogThe statement here is our own: the same inputs, outputs and technique.
A scanner read a page of handwritten algebra and kept only the round brackets, throwing away every other mark. What survives is the string s, holding the brackets in the order they were written; each character of s is either '(' or ')'.
Call a bracket log settled when it reads as a correct nesting. Precisely, a log is settled if it is empty, or if it is one settled log written straight after another, or if it is a settled log with a '(' put in front of it and a ')' put after it.
An editor may type single brackets back into the log at any positions, including the very start and the very end, but may never delete or move a bracket that is already there. Return the fewest brackets the editor has to type so that the log becomes settled.
Examples
Example 1
- Input
- s = "()))(("
- Output
- 4
The first two characters already pair with each other. The two closes that follow have nothing standing before them to pair with, and the two opens at the end have nothing after them, so an open is typed before each of those closes and a close after each of those opens.
Example 2
- Input
- s = ")("
- Output
- 2
The log as scanned has a close before an open. Typing one open at the very start and one close at the very end settles it.
Example 3
- Input
- s = "()"
- Output
- 0
The log already reads as a correct nesting, so the editor types nothing.
Example 4
- Input
- s = ")))((("
- Output
- 6
Each of the three leading closes needs an open typed before it, and each of the three trailing opens needs a close typed after it.
Constraints
- 1 <= s.length <= 1000
- s[i] 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 min_add_to_make_valid(s: str) -> int:public int minAddToMakeValid(String s)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 17 test cases: 17 passed
- Passed: 4 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
- Check if a Parentheses String Can Be ValidReal-world version: Can the Bracket Tape Be BalancedMedium
- Remove Outermost ParenthesesReal-world version: Strip Root Frame MarkersEasy