LeetCode 921: Minimum Add to Make Parentheses Valid Solution
Master LeetCode problem 921 (Minimum Add to Make Parentheses Valid), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To solve this problem, we can use a stack to keep track of the unbalanced parentheses in the string. We iterate through the string, and for each opening parenthesis, we push its index into the stack. If we encounter a closing parenthesis, we check if the stack is empty or the top element in the stack corresponds to an opening parenthesis. If it does, we pop from the stack. At the end, the size of the stack will tell us how many additional parentheses we need to balance the string.
- Time complexity: O(n) where n is the length of the input string.
- Space complexity: O(n) where n is the length of the input string.
:
Solution Code
class Solution {
public int minAddToMakeValid(String s) {
Stack<Integer> stack = new Stack<>();
int count = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
stack.push(i);
} else {
if (!stack.isEmpty() && s.charAt(stack.peek()) == '(') {
stack.pop();
} else {
count++;
}
}
}
return count + stack.size();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 921 (Minimum Add to Make Parentheses Valid)?
This page provides optimized solutions for LeetCode problem 921 (Minimum Add to Make Parentheses Valid) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 921 (Minimum Add to Make Parentheses Valid)?
The time complexity for LeetCode 921 (Minimum Add to Make Parentheses Valid) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 921 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 921 in Java, C++, or Python.