Tensorum
LeetCode 1249 · Parentheses / Bracket Matching

Minimum Remove to Make Valid Parentheses

LeetCode 1249 · Medium · solution, intuition & step-by-step walkthrough

Stack of '(' indices; collect unmatched indices; rebuild.

MediumStringStack
178 msruntime · beats 5%
56.7 MBmemory · beats 100%
1approach
5accepted runs · last 6 Apr 2024

This is how I solved Minimum Remove to Make Valid Parentheses (LeetCode 1249), a medium problem from the Parentheses / Bracket Matching pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

A ')' with no unmatched '(' before it must go; any '(' still unmatched at the end must go too. A stack of open indices finds both kinds.

Approach

  1. 1

    '(' → push its index.

  2. 2

    ')' → pop if possible, else mark it for removal.

  3. 3

    Mark every index left on the stack.

  4. 4

    Rebuild the string skipping marked indices.

How I solved it

Stack of indicesPythonO(n) time
class Solution:
    def minRemoveToMakeValid(self, s):
        stack = []
        indexToBeRemoved = []
        word = ""
        for i in range(len(s)):
            char = s[i]
            if char == "(":
                stack.append(i)
            elif char == ")":
                if not stack:
                    indexToBeRemoved.append(i)  # extra )
                else:
                    stack.pop()
        while stack:
            indexToBeRemoved.append(stack.pop())
        for i in range(len(s)):
            if i not in indexToBeRemoved:
                word += s[i]
        return word
Loading the step-through…

Minimum Remove to Make Valid Parentheses — FAQ

What is the intuition behind Minimum Remove to Make Valid Parentheses?

A ')' with no unmatched '(' before it must go; any '(' still unmatched at the end must go too. A stack of open indices finds both kinds.

How do you solve Minimum Remove to Make Valid Parentheses (LeetCode 1249)?

1. '(' → push its index. 2. ')' → pop if possible, else mark it for removal. 3. Mark every index left on the stack. 4. Rebuild the string skipping marked indices.

What is the time and space complexity of Minimum Remove to Make Valid Parentheses?

Time: O(n) with a set (O(n²) with indexOf). Space: O(n). (Accepted approach: Stack of indices.)

What are common mistakes in Minimum Remove to Make Valid Parentheses?

Checking membership with indexOf on an array is O(n) per character — a set is better.