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.

1021. Remove Outermost Parentheses

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

  1. Initialize an empty string result to store the final output.
  2. Initialize a variable balance to keep track of the balance of parentheses.
  3. Iterate through each character c in the input string s.
  4. If c is an opening parenthesis and balance is greater than 0, add c to the result.
  5. If c is a closing parenthesis and balance is greater than 1, add c to the result.
  6. Update the balance based on the type of parenthesis encountered.
  7. 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.

Back to LeetCode Solutions