Ctrl K

Unwrap and Reverse the Brackets

Medium
You get a string text made of lowercase English letters and parentheses, and the parentheses are properly balanced. For every matching pair of parentheses, reverse whatever lies between them, working from the innermost pairs outward. Return the final string with all parentheses removed.
Example 1
text="x(yz)w" → 'xzyw'

Inside the brackets yz turns into zy, giving xzyw.

Example 2
text="(ab(cd)ef)" → 'fecdba'

First cd → dc, giving abdcef; then the outer pair reverses everything: fecdba.

Example 3
text="()q" → 'q'

Empty brackets simply vanish.

Constraints
  • 1 ≤ len(text) ≤ 2000
  • text consists of lowercase English letters, ( and )
  • The parentheses are balanced
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTidy a Folder Route MediumFour-Operation Calculator MediumEvery Letter Once MediumChecking a Tree Record With Hash Marks MediumLongest Path to a File Medium
loading Python…
Input
text="x(yz)w"
Expected
'xzyw'

Run checks the first 3 tests in your browser. Submit checks all 66 tests on the server, hidden ones included.