Minimum Add to Make Parentheses Valid in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string S of '(' and ')' parentheses, we add the minimum number of parentheses at any positions, so that the resulting parentheses string is valid. A parentheses string is valid if and only if −

  • It is the empty string
  • It can be written as XY (X concatenated with Y), where X and Y are valid strings
  • It can be written as (A), where A is a valid string.

So if the string is like "()))((", then we need to add 4 more parentheses to make the string valid.

To solve this, we will follow these steps −

  • if S is empty, then return 0
  • count := 0, temp is an array, temp_counter := 0
  • for i in S
    • if i is opening parentheses, then insert i into temp
    • otherwise
      • when length of temp > 0 and last element of is opening parentheses, then delete the last element of temp, otherwise insert i into temp
  • return the size of temp.

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def minAddToMakeValid(self, S):
      if not S:
         return 0
      count = 0
      temp = []
      temp_counter = 0
      for i in S:
         if i =='(':
            temp.append(i)
         else:
            if len(temp)>0 and temp[len(temp)-1] =='(':
               temp.pop(len(temp)-1)
            else:
               temp.append(i)
      return len(temp)
ob = Solution()
print(ob.minAddToMakeValid("()))(("))

Input

"()))(("

Output

4
raja
Published on 30-Apr-2020 07:37:16
Advertisements