- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

# 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

- if p is same as "(", then
- return total + temp

Let us see the following implementation to get better understanding −

## Example

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

- Related Questions & Answers
- C++ Program to count minimum problems to be solved to make teams
- Program to find shortest subarray to be removed to make array sorted in Python
- C++ Program to count number of characters to be removed to get good string
- Minimum number of elements to be removed to make XOR maximum using C++.
- Program to find minimum deletions to make string balanced in Python
- Program to count minimum deletions needed to make character frequencies unique in Python
- Program to find minimum number of intervals to be removed to remove overlaps in C++
- Minimum number of elements that should be removed to make the array good using C++.
- Program to count minimum number of operations to flip columns to make target in Python
- Program to count number of minimum swaps required to make it palindrome in Python
- Program to find minimum number of operations to make string sorted in Python
- Program to count minimum k length sublist that can be flipped to make all items of list to 0 in Python
- Program to find minimum number of characters to be added to make it palindrome in Python
- Program to count minimum number of operations required to make numbers non coprime in Python?
- Program to check minimum number of characters needed to make string palindrome in Python

Advertisements