
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Add to Make Parentheses Valid in Python
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
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
Advertisements