
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- Minimum size substring to be removed to make a given string palindromic
- C++ Program to count minimum problems to be solved to make teams
- C++ Program to count number of characters to be removed to get good string
- Program to find shortest subarray to be removed to make array sorted in Python
- Program to find minimum deletions to make string balanced in Python
- Program to count minimum deletions needed to make character frequencies unique in Python
- Minimum characters required to be removed to sort binary string in ascending order
- Minimum number of elements to be removed to make XOR maximum 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 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
- Minimum number of digits required to be removed to make a number divisible by 4

Advertisements