Minimum Remove to Make Valid Parentheses — LeetCode 1249 Python Solution

MediumStackString
Problem
#1249
Pattern
Stack
Reading time
4 min

The problem

Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

Example

Input
s = "lee(t(c)o)de)"
Output
"lee(t(c)o)de"
Explanation
"lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.

Python solution

Python
class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        stk = []
        x = 0
        for c in s:
            if c == ')' and x == 0:
                continue
            if c == '(':
                x += 1
            elif c == ')':
                x -= 1
            stk.append(c)
        x = 0
        ans = []
        for c in stk[::-1]:
            if c == '(' and x == 0:
                continue
            if c == ')':
                x += 1
            elif c == '(':
                x -= 1
            ans.append(c)
        return ''.join(ans[::-1])

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1249. Minimum Remove to Make Valid Parentheses is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1249. Minimum Remove to Make Valid Parentheses?
LeetCode 1249. Minimum Remove to Make Valid Parentheses is rated Medium on LeetCode.
What is the time complexity of LeetCode 1249. Minimum Remove to Make Valid Parentheses?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1249. Minimum Remove to Make Valid Parentheses?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1249. Minimum Remove to Make Valid Parentheses cover?
LeetCode 1249. Minimum Remove to Make Valid Parentheses is tagged Stack and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview