Minimum Remove to Make Valid Parentheses (Leetcode 1249)

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

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        
        count=0
        
        for i in range(len(s)):
            if(s[i]=='('):
                count+=1
            elif(s[i]==')'):
                if(count<=0):
                    s=s[:i]+'#'+s[i+1:]
                else:
                    count-=1
                    
        
        # Now traverse from the back to remove extra 
        # ( 
        for i in range(len(s)-1,-1,-1):
            if(count>0 and s[i]=='('):
                s=s[:i]+'#'+s[i+1:]
                count-=1
        
        ans=''
        
        for i in range(len(s)):
            if(s[i]!='#'):
                ans=ans+s[i]
        
        return ans
        

Last updated