Leetcode 1371 Solution

This article provides solution to leetcode question 1371 (minimum-remove-to-make-valid-parentheses)

https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses

Solution

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        stack = []
        to_remove = []
        for i, ch in enumerate(s):
            if ch == '(':
                stack.append(i)
            elif ch == ')':
                if len(stack) == 0:
                    to_remove.append(i)
                else:
                    stack.pop()

        unsed_set = set(stack + to_remove)

        ans = ""
        for i, ch in enumerate(s):
            if i in unsed_set:
                continue
            ans += ch
        return ans