Reverse Substrings Between Each Pair of Parentheses (LeetCode 1190): Solution and Explanation
Reverse the text inside every matched pair of parentheses, innermost first, and return the result with all brackets removed.
Intuition
The obvious method keeps a stack of partial strings: on ( start a new one, on ) pop it, reverse it and append it to the one below. It is correct, but each reversal copies text, so deeply nested input costs O(n^2).
Look at what a reversal really does to the reading order. Reading (abcd) reversed means: when you reach the (, go to the matching ) and read leftward until you come back to the (, then continue after the ).
So a bracket acts like a wormhole. Stepping onto one moves you to its partner and turns you around. A pair nested inside another flips you twice, which is exactly why a doubly reversed piece reads forward again.
With the partner of every bracket precomputed, one walk over the string reads every letter exactly once, in final order.
Approach: Pair brackets, then walk with direction flips
- Scan once with a stack of open indices. On
), pop the matching(indexjand setpartner[i] = j,partner[j] = i. - Start the walk at
i = 0with directiond = 1. - If
s[i]is a bracket, seti = partner[i]andd = -d. Otherwise appends[i]to the result. - Move
i += dand repeat untilileaves the string. Return the result.
Step-by-step example
s = "(abcd)"
- Pairing:
(at 0 is pushed,)at 5 pops it. partner[0] = 5 and partner[5] = 0. - Walk starts at 0 heading right. It is a bracket, so jump to 5 and turn left.
- Step to 4, 3, 2, 1 and collect d, c, b, a.
- Step to 0, a bracket again: jump to 5 and turn right. The next step is 6, past the end.
- Return "dcba".
Code: Python, Java, C++
1class Solution:
2 def reverseParentheses(self, s: str) -> str:
3 n = len(s)
4 partner = [0] * n
5 stack = []
6 for i, c in enumerate(s):
7 if c == '(':
8 stack.append(i)
9 elif c == ')':
10 j = stack.pop()
11 partner[i], partner[j] = j, i
12 res = []
13 i, d = 0, 1
14 while i < n:
15 if s[i] in '()':
16 i = partner[i]
17 d = -d
18 else:
19 res.append(s[i])
20 i += d
21 return ''.join(res)1class Solution {
2 public String reverseParentheses(String s) {
3 int n = s.length();
4 int[] partner = new int[n];
5 Deque<Integer> stack = new ArrayDeque<>();
6 for (int i = 0; i < n; i++) {
7 if (s.charAt(i) == '(') {
8 stack.push(i);
9 } else if (s.charAt(i) == ')') {
10 int j = stack.pop();
11 partner[i] = j;
12 partner[j] = i;
13 }
14 }
15 StringBuilder res = new StringBuilder();
16 for (int i = 0, d = 1; i < n; i += d) {
17 char c = s.charAt(i);
18 if (c == '(' || c == ')') {
19 i = partner[i];
20 d = -d;
21 } else {
22 res.append(c);
23 }
24 }
25 return res.toString();
26 }
27}1class Solution {
2public:
3 string reverseParentheses(string s) {
4 int n = s.size();
5 vector<int> partner(n), st;
6 for (int i = 0; i < n; i++) {
7 if (s[i] == '(') {
8 st.push_back(i);
9 } else if (s[i] == ')') {
10 int j = st.back();
11 st.pop_back();
12 partner[i] = j;
13 partner[j] = i;
14 }
15 }
16 string res;
17 for (int i = 0, d = 1; i < n; i += d) {
18 if (s[i] == '(' || s[i] == ')') {
19 i = partner[i];
20 d = -d;
21 } else {
22 res += s[i];
23 }
24 }
25 return res;
26 }
27};Time and space complexity
O(n)
The pairing pass reads each character once. In the walk every letter is visited once and every bracket is stepped on exactly twice.
O(n)
The partner array and the stack are O(n), and so is the output.
Other approaches
Stack of partial strings (time O(n^2), space O(n))
Push a new buffer on (; on ) pop the top buffer, reverse it and append it to the buffer below. Simple and accepted for n <= 2000, but deep nesting re-reverses the same letters many times.
Stack of indices with in-place reversal (time O(n^2), space O(n))
Keep a character array. On ), pop the matching ( index and reverse the array slice between them, then drop the brackets at the end. Same quadratic worst case, less allocation.
Common mistakes
- Reversing outer pairs first. The order matters for the stack approach: always finish the innermost pair before the one around it.
- Appending the brackets to the answer. They only steer the walk and must never be output.
- Forgetting to flip the direction after a jump, which would just skip the bracketed text.
- Assuming the answer needs at least one letter. Input like
()is balanced and gives an empty string.
Frequently asked questions
Why does jumping to the partner reverse the text?
After the jump you stand on the closing end of the pair and walk inward in the opposite direction, so you read the inside back to front. When you reach the other end you jump out and turn around again, which restores the original direction outside the pair.
How does nesting work with the walk?
Each pair you enter flips the direction once. A letter inside k pairs is read with k flips applied, which is the same as reversing it k times, exactly what the innermost-first rule produces.
Can the walk loop forever?
No. Each bracket is stepped on exactly twice, once from each side, and each letter once, so the walk ends after about n + number of brackets steps.
Is the O(n^2) stack solution good enough?
For n up to 2000 it passes. The wormhole walk is the follow-up interviewers like to hear because it removes the repeated reversals.