← Home

1190. Reverse Substrings Between Each Pair of Parentheses

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
stackC++Markdown
119

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1190. Reverse Substrings Between Each Pair of Parentheses, the solution in this repository is mainly a stack solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: stack.

The notes already sitting in the source point us in the right direction:

  • Stack, Brute Force
  • https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/383670/JavaC%2B%2BPython-Why-not-O(N)
  • time: O(N^2), space: O(N)

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are reverseParentheses.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Stack, Brute Force
02//https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/383670/JavaC%2B%2BPython-Why-not-O(N)
03//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Reverse Substrings Between Each Pair of Parentheses.
04//Memory Usage: 6.4 MB, less than 100.00% of C++ online submissions for Reverse Substrings Between Each Pair of Parentheses.
05//time: O(N^2), space: O(N)
06class Solution {
07public:
08    string reverseParentheses(string s) {
09        stack<int> openIdxs;
10        string ans = "";
11        
12        for(int i = 0; i < s.size(); i++){
13            switch(s[i]){
14                case '(':{
15                    openIdxs.push(ans.size());
16                    break;
17                }case ')':{
18                    int openIdx = openIdxs.top(); openIdxs.pop();
19                    reverse(ans.begin() + openIdx, ans.end());
20                    break;
21                }default:{
22                    ans += s[i];
23                    break;
24                }
25            }
26        }
27        
28        return ans;
29    }
30};
31
32//Wormholes, two-pass
33//https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/383670/JavaC%2B%2BPython-Why-not-O(N)
34//Runtime: 4 ms, faster than 56.64% of C++ online submissions for Reverse Substrings Between Each Pair of Parentheses.
35//Memory Usage: 6.7 MB, less than 100.00% of C++ online submissions for Reverse Substrings Between Each Pair of Parentheses. 
36//time: O(N), space: O(N)
37class Solution {
38public:
39    string reverseParentheses(string s) {
40        int N = s.size();
41        string ans = "";
42        stack<int> openIdxs;
43        map<int, int> pair;
44        
45        for(int i = 0; i < N; i++){
46            if(s[i] == '('){
47                openIdxs.push(i);
48            }else if(s[i] == ')'){
49                int j = openIdxs.top(); openIdxs.pop();
50                pair[i] = j;
51                pair[j] = i;
52            }
53        }
54        
55        for(int i = 0, d = 1; i < N; i += d){
56            if(s[i] == '(' || s[i] == ')'){
57                i = pair[i];
58                d = -d;
59                // cout << i << " " << pair[i] << " " << d << endl;
60            }else{
61                ans += s[i];
62            }
63            // cout << i << " " << ans << endl;
64        }
65        
66        return ans;
67    }
68};

Cost

Complexity

Time
O(N), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.