Minimum Add to Make Parentheses Valid — LeetCode 921 Python Solution
- Problem
- #921
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
A parentheses string is valid if and only if: It is the empty string, It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. You are given a parentheses string s.
Example
- Input
- s = "())"
- Output
- 1
Python solution
class Solution:
def minAddToMakeValid(self, s: str) -> int:
stk = []
for c in s:
if c == ')' and stk and stk[-1] == '(':
stk.pop()
else:
stk.append(c)
return len(stk)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the length of the string s auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 921. Minimum Add to Make Parentheses Valid is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 921. Minimum Add to Make Parentheses Valid?
- LeetCode 921. Minimum Add to Make Parentheses Valid is rated Medium on LeetCode.
- What is the time complexity of LeetCode 921. Minimum Add to Make Parentheses Valid?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 921. Minimum Add to Make Parentheses Valid?
- The Python solution on this page uses O(n), where n is the length of the string s auxiliary space.
- What topics does LeetCode 921. Minimum Add to Make Parentheses Valid cover?
- LeetCode 921. Minimum Add to Make Parentheses Valid is tagged Stack, Greedy and String on LeetCode.