Program to count minimum invalid parenthesis to be removed to make string correct in Python


Suppose we have a string of parentheses; we have to write a function to compute the minimum number of parentheses to be removed to make the string correct (each open parenthesis is eventually closed).

So, if the input is like "(()))(", then the output will be 2, as the correct string is "(())", remove ")(".

To solve this, we will follow these steps −

  • total := 0, temp := 0
  • for each p in s, do
    • if p is same as "(", then
      • total := total + 1
    • otherwise when p is same as ")" and total is not 0, then
      • total := total - 1
    • otherwise,
      • temp := temp + 1
  • return total + temp

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s):
      total = 0
      temp = 0
      for p in s:
         if p == "(":
            total += 1
         elif p == ")" and total:
            total -= 1
         else:
            temp += 1
      return total + temp
ob1 = Solution()
string = "(()))("
print(ob1.solve(string))

Input

"(()))("

Output

2

Updated on: 20-Oct-2020

344 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements