LeetCode 1249: Minimum Remove to Make Valid Parentheses Solution
Master LeetCode problem 1249 (Minimum Remove to Make Valid Parentheses), 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 indices of opening parentheses ( that are not matched with a closing parenthesis ). We will also use a set to keep track of the indices of closing parentheses ) that are not matched with an opening parenthesis (.
- Iterate through the input string
sto find and store the indices of mismatched parentheses in the stack and set. - Construct a new string by ignoring the characters at the indices stored in the stack and set.
- Return the constructed string as the minimum removed valid parentheses string.
Time Complexity: O(n) where n is the length of the input string s. Space Complexity: O(n) for the stack and set.
Solution Code
class Solution {
public String minRemoveToMakeValid(String s) {
Stack<Integer> stack = new Stack<>();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
stack.push(i);
} else if (c == ')') {
if (!stack.isEmpty()) {
stack.pop();
} else {
set.add(i);
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (!stack.isEmpty() && stack.peek() == i) {
stack.pop();
} else if (set.contains(i)) {
continue;
} else {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1249 (Minimum Remove to Make Valid Parentheses)?
This page provides optimized solutions for LeetCode problem 1249 (Minimum Remove to Make Valid Parentheses) 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 1249 (Minimum Remove to Make Valid Parentheses)?
The time complexity for LeetCode 1249 (Minimum Remove to Make Valid Parentheses) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1249 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1249 in Java, C++, or Python.