Given a string s made of lowercase letters and the characters ( and ), remove the minimum number of parentheses so that the remaining string is valid. Return every distinct valid string that can be obtained with that minimum number of removals.
Function Signature
def remove_invalid_parentheses(s: str) -> list[str]:
...
Rules
-
A string is valid when every
)
closes an earlier
(
that is still open and no
(
is left open at the end. Letters do not affect validity, and the empty string is valid.
-
Only parentheses may be removed. Letters always stay, and the remaining characters keep their original order.
-
Each distinct result appears once, even when different removal choices produce the same string.
-
Return the results sorted in ascending lexicographic order, using Python's default string comparison (
(
sorts before
)
, and both sort before lowercase letters).
-
When the only valid result is the empty string, return
[""]
.
Constraints
-
1 <= len(s) <= 25
-
s
consists of lowercase English letters and the characters
(
and
)
.
Examples
Input: s = "()())()"
Output: ["(())()", "()()()"]
There is one ) too many, so one removal is the minimum. Removing the ) at index 1 gives "(())()", and removing the one at index 3 or index 4 gives "()()()" both times, so it is listed once.
Input: s = "(a)())()"
Output: ["(a())()", "(a)()()"]
The letter stays in place. Removing the ) at index 2 gives "(a())()", and removing the one at index 4 or index 5 gives "(a)()()".
Input: s = ")("
Output: [""]
Removing one character leaves "(" or ")", and neither is valid. Both must go, which leaves the empty string.