Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Remove Outermost Parentheses in a Valid Parentheses String
Optimal Solution



Problem Statement

Given a valid parentheses string s, your task is to remove the outermost parentheses from each primitive valid parentheses substring.

Return the final processed string after removing the outermost parentheses from every primitive.

Examples

InputOutputDescription
"(()())(())""()()()"Two primitive parts: "(()())" → "()()", "(())" → "()"
"(()())(())(()(()))""()()()()(())"Removes outer parentheses from each primitive group
"()()"""Each "()" is primitive, and its outer parentheses are removed
"((()))""(())"Single primitive, outermost removed
""""Empty input returns empty output

Solution

To solve this problem, we need to understand what it means to remove the outermost parentheses from a primitive group in a valid parentheses string.

A primitive parentheses string is one that is valid (i.e., balanced) and cannot be divided further into smaller valid parts. For example, "(())" and "()" are primitives, but "(()())(())" is not a primitive — it's made of multiple primitives.

Our goal is to go through the input and for every such primitive group, remove its first '(' and last ')'. For example, in "(()())", the primitive is the whole string, and removing its outermost parentheses gives "()()".

How We Approach This

We walk through the string character by character. As we go, we use a counter open to track how deep we are in the parentheses nesting:

  • When we see '(', we increase the nesting count.
  • When we see ')', we decrease the nesting count.

But here's the trick: we don't include the first '(' when open goes from 0 to 1 (this is the outermost), and we don't include the ')' that causes open to go back to 0 (this is the closing of the outermost).

Example Cases

Let’s take "(()())(())" as an example:

  • The first primitive is "(()())" → we remove the outermost '(', ')' → becomes "()()"
  • The second primitive is "(())" → becomes "()"
  • Final result: "()()()"

Edge Cases

  • If the input is an empty string "", there’s nothing to process, so we return "".
  • If the string consists only of "()()", each pair is its own primitive, and both outer parentheses are removed, leaving an empty string.
  • If the input is deeply nested like "((()))", then removing the outermost parentheses gives "(())".

This method works efficiently in one pass through the string and uses only a simple counter — making it an optimal solution.

Visualization

Algorithm Steps

  1. Given a valid parentheses string s.
  2. Initialize an empty result string and a counter open = 0.
  3. Iterate through each character in the string:
  4. → If the character is '(', increment open.
  5. → If open > 1 after incrementing, add '(' to the result.
  6. → If the character is ')', decrement open.
  7. → If open > 0 before decrementing, add ')' to the result.
  8. By skipping the first '(' and the last ')' of each primitive, we effectively remove the outermost parentheses.
  9. Return the final result string.

Code

Python
JavaScript
Java
C++
C
def remove_outer_parentheses(s):
    result = []
    open_count = 0
    
    for char in s:
        if char == '(':
            if open_count > 0:
                result.append(char)
            open_count += 1
        else:
            open_count -= 1
            if open_count > 0:
                result.append(char)

    return ''.join(result)

# Sample Input
s = "(()())(())"
print("Result:", remove_outer_parentheses(s))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M