Reverse Substrings Between Each Pair of Parentheses — LeetCode 1190 Python Solution

MediumStackString
Problem
#1190
Pattern
Stack
Reading time
2 min

The problem

You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one.

Example

Input
s = "(abcd)"
Output
"dcba"

Python solution

Python
class Solution:
    def reverseParentheses(self, s: str) -> str:
        stk = []
        for c in s:
            if c == ")":
                t = []
                while stk[-1] != "(":
                    t.append(stk.pop())
                stk.pop()
                stk.extend(t)
            else:
                stk.append(c)
        return "".join(stk)

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n), where n is the length of the string s auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses?
LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses is rated Medium on LeetCode.
What is the time complexity of LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses?
The Python solution on this page uses O(n), where n is the length of the string s auxiliary space.
What topics does LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses cover?
LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses is tagged Stack and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview