Remove Outermost Parentheses

Gulshan KumarGulshan Kumar
2 min read

A valid parentheses string is either empty "", "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.

  • For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.

A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings.

Given a valid parentheses string s, consider its primitive decomposition: s = P<sub>1</sub> + P<sub>2</sub> + ... + P<sub>k</sub>, where P<sub>i</sub> are primitive valid parentheses strings.

Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.

LeetCode Problem - 1021

import java.util.Stack;

class Solution {
    // Method to remove outermost parentheses from a given string
    public String removeOuterParentheses(String s) {
        // StringBuilder to store the result
        StringBuilder ans = new StringBuilder();

        // Stack to keep track of parentheses
        Stack<Character> stack = new Stack<>();

        // Iterate through the characters of the string
        for (int i = 0; i < s.length(); i++) {
            char currentChar = s.charAt(i);

            // If current character is '(', check if it's not the outermost '('
            if (currentChar == '(') {
                if (!stack.isEmpty()) {
                    ans.append(currentChar);
                }
                stack.push(currentChar);
            } 
            // If current character is ')', check if it's not the outermost ')'
            else {
                stack.pop();
                if (!stack.isEmpty()) {
                    ans.append(currentChar);
                }
            }
        }

        // Return the result as a string
        return ans.toString();
    }
}
0
Subscribe to my newsletter

Read articles from Gulshan Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gulshan Kumar
Gulshan Kumar

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman. I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.