- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Minimum Remove to Make Valid Parentheses in C++
- Program to find minimum remove required to make valid parentheses in Python
- Minimum number of Parentheses to be added to make it valid in C++
- Longest Valid Parentheses in Python
- Valid Parentheses in C++
- Minimum edges required to add to make Euler Circuit in Python
- Maximum Nesting Depth of Two Valid Parentheses Strings in Python
- Finding the longest valid parentheses JavaScript
- Program to find minimum insertions to balance a parentheses string using Python
- Different Ways to Add Parentheses in C++
- Minimum edges required to add to make Euler Circuit in C++
- Generate Parentheses in Python
- Minimum number of elements to add to make median equals x using C++.
- Minimum removals from array to make GCD Greater in Python
- Program to find minimum moves to make array complementary in Python

Advertisements