#1190

Reverse Substrings Between Each Pair of Parentheses

Medium
StringStackStackRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a stack allows us to efficiently manage the nested structure of parentheses. We push characters onto the stack until we find a closing parenthesis, at which point we pop from the stack until we reach the corresponding opening parenthesis, reversing the substring in the process.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty stack.
  2. 2Step 2: Iterate through each character in the string.
  3. 3Step 3: If the character is '(', push it onto the stack.
  4. 4Step 4: If the character is ')', pop from the stack until '(' is found, reverse the popped characters, and push the reversed substring back onto the stack.
  5. 5Step 5: After processing all characters, join all elements in the stack to form the final result.
solution.py13 lines
1def reverseParentheses(s):
2    stack = []
3    for char in s:
4        if char == ')':
5            temp = ''
6            while stack and stack[-1] != '(': 
7                temp += stack.pop()
8            stack.pop()  # pop the '('
9            for c in temp:
10                stack.append(c)
11        else:
12            stack.append(char)
13    return ''.join(stack)

Complexity note: The optimal solution runs in linear time because we process each character once, and the stack operations (push/pop) are constant time. The space complexity is linear due to the stack storing characters.

  • 1Using a stack simplifies handling nested structures.
  • 2Reversing substrings can be efficiently managed with stack operations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.