Trains the technique from
LeetCode 921Minimum Add to Make Parentheses ValidThis 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 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.
Example 1
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
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
The log already reads as a correct nesting, so the editor types nothing.
Example 4
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.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def min_add_to_make_valid(s: str) -> int:public int minAddToMakeValid(String s)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.