Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Minimum Add to Make Parentheses Valid in Python
When we have a string of parentheses, we need to find the minimum number of parentheses to add to make it valid. A valid parentheses string follows these rules ?
- 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
For example, if the string is "()))((", we need to add 4 more parentheses to make it valid.
Algorithm
We use a stack-based approach to track unmatched parentheses ?
- If the string is empty, return 0
- Use a stack to track unmatched opening parentheses
- For each character:
- If it's an opening parenthesis '(', push it to the stack
- If it's a closing parenthesis ')':
- If stack has an unmatched '(', pop it (they match)
- Otherwise, push ')' to stack (unmatched closing)
- Return the stack size (total unmatched parentheses)
Example
class Solution:
def minAddToMakeValid(self, S):
if not S:
return 0
stack = []
for char in S:
if char == '(':
stack.append(char)
else: # char == ')'
if len(stack) > 0 and stack[-1] == '(':
stack.pop() # Match found, remove the '('
else:
stack.append(char) # Unmatched ')'
return len(stack)
# Test the solution
ob = Solution()
print(ob.minAddToMakeValid("()))(("))
4
How It Works
Let's trace through the example "()))((" ?
-
'('? stack:['('] -
')'? matches with '(', stack:[] -
')'? no match, stack:[')'] -
')'? no match, stack:[')',')')'] -
'('? stack:[')',')', '('] -
'('? stack:[')',')', '(', '(']
Final stack size is 4, so we need to add 4 parentheses.
Optimized Solution
We can solve this without using extra space by counting unmatched parentheses ?
def minAddToMakeValid(S):
open_needed = 0 # Count of unmatched '('
close_needed = 0 # Count of unmatched ')'
for char in S:
if char == '(':
open_needed += 1
elif char == ')':
if open_needed > 0:
open_needed -= 1 # Match found
else:
close_needed += 1 # Unmatched ')'
return open_needed + close_needed
# Test the optimized solution
print(minAddToMakeValid("()))(("))
print(minAddToMakeValid("((("))
print(minAddToMakeValid(")))"))
print(minAddToMakeValid("()()"))
4 3 3 0
Comparison
| Approach | Space Complexity | Time Complexity | Best For |
|---|---|---|---|
| Stack-based | O(n) | O(n) | Easy to understand |
| Counter-based | O(1) | O(n) | Space-efficient |
Conclusion
Both approaches work effectively. The stack method is more intuitive, while the counter method is space-efficient with O(1) space complexity. Choose based on your memory constraints and code clarity preferences.
