Program to Reverse a Substring Enclosed Within Brackets in Python

When working with strings containing parentheses, we often need to reverse the content within brackets. This problem requires us to reverse every substring enclosed within parentheses in a recursive manner.

For example, if the input string is "back(aps)ce", we need to reverse "aps" to get "spa", resulting in "backspace".

Algorithm Approach

We'll use a two-phase approach ?

  • Phase 1: Create a mapping of matching parentheses using a stack

  • Phase 2: Traverse the string and reverse content within brackets recursively

Step-by-Step Solution

Phase 1: Map Matching Brackets

First, we identify which opening bracket matches which closing bracket ?

def find_matching_brackets(s):
    close = {")": {}, "(": {}}
    stack = []
    
    for i, char in enumerate(s):
        if char == "(":
            stack.append(i)
        elif char == ")":
            opening_pos = stack.pop()
            close[")"][i] = opening_pos  # closing -> opening
            close["("][opening_pos] = i  # opening -> closing
    
    return close

# Example
s = "back(aps)ce"
brackets = find_matching_brackets(s)
print("Bracket mapping:", brackets)
Bracket mapping: {')': {8: 4}, '(': {4: 8}}

Phase 2: Recursive Traversal

Now we traverse the string, reversing direction when we encounter brackets ?

def reverse_parentheses(s):
    # Phase 1: Map matching brackets
    close = {")": {}, "(": {}}
    stack = []
    
    for i, char in enumerate(s):
        if char == "(":
            stack.append(i)
        elif char == ")":
            opening_pos = stack.pop()
            close[")"][i] = opening_pos
            close["("][opening_pos] = i
    
    # Phase 2: Traverse with direction changes
    result = []
    
    def traverse(direction, start):
        # Determine which bracket ends this direction
        end_bracket = "(" if direction == -1 else ")"
        other_bracket = "(" if end_bracket == ")" else ")"
        
        while start < len(s) and s[start] != end_bracket:
            if s[start] == other_bracket:
                # Found a bracket - change direction and jump to its pair
                next_pos = close[other_bracket][start] - direction
                traverse(-direction, next_pos)
                start = close[other_bracket][start] + direction
            else:
                # Regular character - add to result
                result.append(s[start])
                start += direction
    
    traverse(1, 0)
    return "".join(result)

# Test the function
test_string = "back(aps)ce"
output = reverse_parentheses(test_string)
print(f"Input: {test_string}")
print(f"Output: {output}")
Input: back(aps)ce
Output: backspace

Complete Solution

Here's the complete implementation with additional test cases ?

class Solution:
    def solve(self, s):
        result = []
        close = {")": {}, "(": {}}
        stack = []
        
        # Map matching brackets
        for i, char in enumerate(s):
            if char == "(":
                stack.append(i)
            elif char == ")":
                opening_pos = stack.pop()
                close[")"][i] = opening_pos
                close["("][opening_pos] = i
        
        def traverse(s, direction, start, close=close, result=result):
            end_bracket = "(" if direction == -1 else ")"
            other_bracket = "(" if end_bracket == ")" else ")"
            
            while start < len(s) and s[start] != end_bracket:
                if s[start] == other_bracket:
                    traverse(s, -direction, close[other_bracket][start] - direction)
                    start = close[other_bracket][start] + direction
                else:
                    result.append(s[start])
                    start += direction
        
        traverse(s, 1, 0)
        return "".join(result)

# Test with multiple examples
solution = Solution()

test_cases = [
    "back(aps)ce",
    "(abcd)",
    "(u(love)i)",
    "(ed(et(oc))el)"
]

for test in test_cases:
    output = solution.solve(test)
    print(f"Input: '{test}' ? Output: '{output}'")
Input: 'back(aps)ce' ? Output: 'backspace'
Input: '(abcd)' ? Output: 'dcba'
Input: '(u(love)i)' ? Output: 'iloveu'
Input: '(ed(et(oc))el)' ? Output: 'leetcode'

How It Works

Step Process Example: "back(aps)ce"
1 Map brackets Position 4 '(' maps to position 8 ')'
2 Traverse left to right Read 'b', 'a', 'c', 'k'
3 Hit '(' - reverse direction Jump to ')' and read backwards: 's', 'p', 'a'
4 Continue forward Read 'c', 'e'

Conclusion

This solution uses stack-based bracket matching and bidirectional traversal to reverse parenthetical content. The algorithm runs in O(n) time and efficiently handles nested brackets by changing traversal direction at each bracket pair.

Updated on: 2026-03-25T14:05:20+05:30

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements