Skip to content
LEETFLIX

Reverse Substrings Between Each Pair of Parentheses

Solve on LeetCode

Medium · stack solution for Reverse Substrings Between Each Pair of Parentheses. Python, Go, and a step-by-step animation.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses. The copyrighted prompt is on LeetCode. This page is a working stack solution for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

s =
()[]{}

Output

true

Every closer matches the current top. The stack ends empty.

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Reverse Substrings Between Each Pair of Parentheses — stack

Push openers; a closer is legal only if it matches the current top. Built for LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses.

The stack is the nest of brackets that are still open. A mismatch or a leftover opener at the end is an immediate no.

Algorithm

  1. On an opener, push.
  2. On a closer, the top must be its partner — otherwise reject.
  3. Return true only if the stack is empty at the end.
Time
O(n)
Space
O(n)
Solution.py
class Solution:    def reverseSubstringsBetweenEachPairOfParentheses(self, s: str) -> bool:        pairs = {")": "(", "]": "[", "}": "{"}        stack: list[str] = []        for ch in s:            if ch in pairs:                if not stack or stack[-1] != pairs[ch]:                    return False                stack.pop()            else:                stack.append(ch)        return not stack
Watch this run

03

Interactive walkthrough

Playing “Reverse Substrings Between Each Pair of Parentheses — stack”. Edit the input, hit Run, then scrub.

Approach: Reverse Substrings Between Each Pair of Parentheses — stack

Loading animation…