Skip to content

visual walkthrough

Minimum Remove to Make Valid Parentheses

MediumMatching / ParsingReported at: MetaAmazonMicrosoft+4

Tracking indices of unmatched brackets; a frequent Meta question.

Solve on LeetCode

The idea

A bracket is "extra" if it can never be matched. A ')' with nothing open before it is extra. Any '(' still unmatched at the end is extra. Everything else stays, so the result is the fewest removals possible.

A stack of indices finds both kinds in one pass; two counter passes find them without a stack.

Complexity

approachtimespace
Stack of indicesO(n)O(n)
Two passes with countersO(n)O(1) extra

More walkthroughs