Minimum Remove to Make Valid Parentheses

Implement minRemoveToValid

Given a string s containing lowercase letters and parentheses, remove the minimum number of parentheses so that what remains is valid — every '(' has a matching ')' after it, and every ')' has a matching '(' before it. Any one valid result is accepted. Repeatedly rescanning for the next offending bracket (from the left, then from the right) works, but restarts from scratch after every single removal. A single left-to-right pass with a stack of unmatched-'(' indices resolves everything without a single rescan: a ')' either matches something already open (pop it) or clearly has nothing to match (mark it for removal, immediately — no future character can ever change that). Whatever '(' indices are still on the stack once the string ends were never matched either, so those get marked too. One pass decides the fate of every character, since bracket matching only ever depends on what came before, never on what comes after.

Example 1:

Input: s = "mo)ve(m)ent"

Output: "move(m)ent"

Example 2:

Input: s = "x(y))z("

Output: "x(y)z"

Example 3:

Input: s = "(a(b(c"

Output: "abc"

+ 3 hidden test cases run on Submit.

Constraints:

  • 1 ≤ s.length ≤ 15
  • s consists of lowercase English letters and the characters '(' and ')'
  • Any valid resulting string is accepted — there may be more than one

s =

mo)ve(m)ent