Trains the technique from
LeetCode 1249Minimum Remove to Make Valid ParenthesesThis 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 small macro language writes each step as a string s of lowercase letters
and the round brackets ( and ).
Brackets are meant to nest. Reading s from left to right, a ) closes the
nearest ( to its left that nothing has closed yet. A step is well formed when
every bracket ends up with a partner under that rule.
The linter repairs a step that is not well formed by deleting brackets, and it
deletes as few as it can. Which ones go is pinned down: pair the brackets up by
the nearest-open rule above, then delete every ) that found no open bracket to
close and every ( that never got closed. Letters are never deleted, and every
surviving character keeps its original position relative to the others.
Return the string the linter produces.
Example 1
The `)` at index 2 has no open bracket waiting to its left, so it is deleted. The `(` at index 4 is closed by the `)` at index 8, so that pair and every letter stay.
Example 2
The `)` at index 5 closes the nearest unclosed open bracket to its left, which is the `(` at index 3. The `(` at index 1 is then left without a partner, so that is the character deleted.
Example 3
The `)` at index 2 closes the `(` at index 0. The open brackets at indices 3 and 4 are never closed, so both are deleted.
Example 4
There are no brackets to pair, so nothing is deleted.
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_remove_to_make_valid(s: str) -> str:public String minRemoveToMakeValid(String s)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.