921. Minimum Add to Make Parentheses Valid
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.
:
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();
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.