Skip to main content
Back to problems
Leetcode
Medium
Strings
Stacks
Recursion
Amazon
1190. Reverse Substrings Between Each Pair of Parentheses

Reverse every substring enclosed by matching parentheses, then remove the parentheses from the final result.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.

Reverse Substrings Between Each Pair of Parentheses

gfg
Problem Statement

You are given a string s consisting of lowercase English letters and parentheses ( and ).

Process the string by repeatedly finding any matching pair of parentheses, reversing the substring inside that pair, and removing the parentheses themselves. Nested parentheses should be handled correctly, so inner reversals affect the text that outer pairs later reverse.

Return the final string after all parentheses have been removed and all reversals have been applied.

Input Format

  • A single string s.
  • s contains lowercase letters and the characters ( and ).

Output Format

  • Return the transformed string after reversing the content inside each matching parenthesis pair and removing all parentheses.

Constraints

  • The string contains balanced parentheses.
  • 1 <= s.length.
  • s contains only lowercase letters and parentheses.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "(abcd)"

Output

"dcba"

Explanation

The only parenthesized substring is abcd, which becomes dcba after reversal.

Example 2

Input

s = "(u(love)i)"

Output

"iloveu"

Explanation

First reverse love to get ove l in the inner segment effect, then reverse the outer segment to obtain iloveu after removing parentheses.

Show 1 more example

Example 3

Input

s = "a(bcdefghijkl(mno)p)q"

Output

"apmnolkjihgfedcbq"

Explanation

The inner substring mno becomes onm, and then the larger parenthesized section is reversed with that transformed content.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.