LeetCode 1021: Remove Outermost Parentheses Solution
Master LeetCode problem 1021 (Remove Outermost Parentheses), a easy 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 iterate through the input string s and keep track of the outermost parentheses. We can use a counter to keep track of the balance of parentheses. When the counter is 0, we know we have reached the end of a primitive valid parentheses string. We can then remove the outermost parentheses of that primitive string.
Algorithm
- Initialize an empty string
resultto store the final output. - Initialize a variable
balanceto keep track of the balance of parentheses. - Iterate through each character
cin the input strings. - If
cis an opening parenthesis andbalanceis greater than 0, addcto theresult. - If
cis a closing parenthesis andbalanceis greater than 1, addcto theresult. - Update the balance based on the type of parenthesis encountered.
- Return the
result.
Time Complexity
The time complexity of this algorithm is O(n), where n is the length of the input string s.
Space Complexity
The space complexity of this algorithm is O(n), where n is the length of the input string s.
Solution Code
class Solution {
public String removeOuterParentheses(String s) {
StringBuilder result = new StringBuilder();
int balance = 0;
for (char c : s.toCharArray()) {
if (c == '(' && balance++ > 0) {
result.append(c);
}
if (c == ')' && balance-- > 1) {
result.append(c);
}
}
return result.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1021 (Remove Outermost Parentheses)?
This page provides optimized solutions for LeetCode problem 1021 (Remove Outermost 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 1021 (Remove Outermost Parentheses)?
The time complexity for LeetCode 1021 (Remove Outermost Parentheses) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1021 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1021 in Java, C++, or Python.