Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Remove Outermost Parentheses | Leetcode 1021 | Stack Depth Counting Solution
    Data Structures & Algorithms

    Remove Outermost Parentheses | Leetcode 1021 | Stack Depth Counting Solution

    Anirudh KhuranaBy Anirudh Khurana1 September 2025No Comments3 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of a question to solve Remove outermost Paranthesis
    Share
    Facebook Twitter LinkedIn Pinterest Email

    You are given a valid parentheses string s. Your task is to remove the outermost parentheses of every primitive substring.

    • A primitive string is a non-empty valid parentheses string that cannot be split into two smaller non-empty valid parentheses strings.
    • You need to return the final string after removing the outermost parentheses from each primitive.

    Here’s the [Problem Link] to begin with.


    Examples

    Example 1

    Input: s = "(()())(())"
    Output: "()()()"
    Explanation:
    Primitive parts: "(()())" and "(())"
    After removing outermost parentheses → "()()" + "()"
    Final answer = "()()()"

    Example 2

    Input: s = "(()())(())(()(()))"
    Output: "()()()()(())"
    Explanation:
    Primitives: "(()())", "(())", "(()(()))"
    After removing outermost → "()()", "()", "(())"
    Final = "()()()()(())"

    Example 3

    Input: s = "()()"
    Output: ""
    Explanation:
    Each primitive is "()" and removing the outer parentheses leaves nothing.

    Intuition and Approach

    The key idea is to track the nesting depth of parentheses:

    1. Use a counter count to track how many open parentheses are currently active.
      • Increment count when you see '('.
      • Decrement count when you see ')'.
    2. For each '(':
      • If count > 0, it means this '(' is not the outermost one, so add it to result.
      • Otherwise, skip it because it’s the outermost opening parenthesis of a primitive.
    3. For each ')':
      • First decrement count.
      • If count > 0, it means this ')' is not the outermost one, so add it to result.
      • Otherwise, skip it because it’s the outermost closing parenthesis of a primitive.

    By following this rule, the outermost parentheses of each primitive are excluded.


    Code Implementation

    class Solution:
        def removeOuterParentheses(self, s: str) -> str:
            result = ""
            count = 0
            for ch in s:
                if ch == "(":
                    count += 1
                    if count > 1:
                        result += ch
                else:
                    count -= 1
                    if count > 0:
                        result += ch
            return result

    Code Explanation

    • result: stores the final string after removing outermost parentheses.
    • count: tracks the current nesting depth of parentheses.
    • For every character:
      • If it’s '(': increase depth, add it only if depth is greater than 1.
      • If it’s ')': decrease depth, add it only if depth is still greater than 0 after decrement.
    • This ensures that only inner parentheses are added, while outermost ones are skipped.

    Dry Run

    Input: s = "(()())(())"

    Step by step:

    • '(' → count = 1 → skip (outermost)
    • '(' → count = 2 → add "("
    • ')' → count = 1 → add ")"
    • '(' → count = 2 → add "("
    • ')' → count = 1 → add ")"
    • ')' → count = 0 → skip (outermost closed)

    First primitive processed → "()()".

    Repeat for second primitive (()) → "()".

    Final result: "()()()".


    Time and Space Complexity

    • Time Complexity: O(N) because we process each character once.
    • Space Complexity: O(N) for the result string (ignoring input storage).

    Conclusion

    The Remove Outermost Parentheses problem can be solved neatly using a counter to track depth.
    By skipping characters at depth 1 (outermost), we remove the unwanted parentheses and keep the inner structure intact.

    This is a classic example of using nesting depth tracking instead of a full stack, making the solution both simple and efficient.


    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Easy Strings
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleBoundary Traversal of Binary Tree – Detailed Explanation
    Next Article Reverse Words in a String | Leetcode 151 | Split and Reverse Approach
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Data Structures & Algorithms

    DSA Interview Cheat Sheet: All Patterns You Need to Know

    4 April 2026
    Data Structures & Algorithms

    Symmetric Tree | Leetcode 101 | Recursive DFS Approach

    2 September 2025
    Data Structures & Algorithms

    Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches

    2 September 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (4)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (1)
    Recent Posts

    Confusion Matrix in Machine Learning: An Interactive Guide

    21 October 2026

    100 SQL Interview Questions with Queries and Answers (Freshers to Experienced)

    17 October 2026

    Logistic Regression in Machine Learning: Explained Visually (with Python)

    17 October 2026

    Linear Regression in Machine Learning: Explained Visually (with Python)

    17 October 2026

    100 Python Interview Questions and Answers for Freshers and Experienced (Free PDF)

    17 October 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.