Reverse Substrings Between Each Pair of Parentheses - Problem

You are given a string s that consists of lowercase English letters and brackets.

Reverse the strings in each pair of matching parentheses, starting from the innermost one.

Your result should not contain any brackets.

Input & Output

Example 1 — Nested Parentheses
$ Input: s = "(u(love)i)"
Output: iloveu
💡 Note: First reverse innermost "love" → "evol", giving "(uevoli)". Then reverse "uevoli" → "iloveu" and remove brackets.
Example 2 — Multiple Groups
$ Input: s = "(ed(et(oc))el)"
Output: leetcode
💡 Note: Process innermost: "oc" → "co", then "etco" → "octe", then "edocteel" → "leetcode".
Example 3 — No Parentheses
$ Input: s = "abcd"
Output: abcd
💡 Note: No parentheses to process, return string as-is.

Constraints

  • 1 ≤ s.length ≤ 2000
  • s only contains lowercase English letters and parentheses
  • It is guaranteed that all parentheses are balanced

Visualization

Tap to expand
Reverse Substrings Between ParenthesesStep 1: Input(u(love)i)Step 2: Process Innermost(love)evol(uevoli)Step 3: Process Outer(uevoli)iloveuFinal Result:iloveuProcess from innermost parentheses outward, reversing at each level
Understanding the Visualization
1
Input
String with nested parentheses: "(u(love)i)"
2
Process Innermost
Reverse "love" → "evol", giving "(uevoli)"
3
Process Outer
Reverse "uevoli" → "iloveu", remove brackets
Key Takeaway
🎯 Key Insight: Use stack to handle nested structure naturally - each parentheses level becomes a stack frame
Asked in
Amazon 25 Google 18 Microsoft 12 Facebook 8
125.0K Views
Medium Frequency
~15 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen