Reverse Substrings Between Each Pair of Parentheses - Problem

You are given a string s consisting of lowercase English letters and parentheses. Your task is to reverse the substrings enclosed within each pair of matching parentheses, starting from the innermost pairs and working outward.

Think of it like peeling an onion - you process the innermost parentheses first, reverse their content, then move to the outer layers. The final result should not contain any parentheses.

Example: If you have "(abcd)", you reverse "abcd" to get "dcba". For nested cases like "(u(love)i)", you first reverse "love" to get "evol", making it "(uevoli)", then reverse the outer content to get "iloveu".

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "(abcd)"
โ€บ Output: "dcba"
๐Ÿ’ก Note: We have one pair of parentheses containing "abcd". Reversing it gives "dcba" and we remove the parentheses.
example_2.py โ€” Nested Parentheses
$ Input: s = "(u(love)i)"
โ€บ Output: "iloveu"
๐Ÿ’ก Note: First reverse innermost "love" โ†’ "evol", giving "(uevoli)". Then reverse "uevoli" โ†’ "iloveu".
example_3.py โ€” Multiple Pairs
$ Input: s = "(ed(et(oc))el)"
โ€บ Output: "leetcode"
๐Ÿ’ก Note: Process innermost first: "oc" โ†’ "co", then "etco" โ†’ "octe", finally "edocteel" โ†’ "leetcode".

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
Processing "(u(love)i)" like Russian Nesting DollsOuter LevelResult: "iloveu"Inner Level"uevoli" โ†’ reverseInnermost"love" โ†’ "evol"uloveiProcessing Steps:1. Process innermost: "love" โ†’ "evol"2. Merge with outer: "u" + "evol" + "i"3. Reverse outer: "uevoli" โ†’ "iloveu"Stack Visualization""โ†’ u โ†’"u""love"reverse"uevol"
Understanding the Visualization
1
Enter outer doll
Start processing the outermost parentheses level
2
Dive deeper
When we find '(', we go to the next nesting level
3
Hit the core
Process the innermost content first
4
Reverse and bubble up
Reverse content and merge with the previous level
5
Complete the message
Continue until all levels are processed
Key Takeaway
๐ŸŽฏ Key Insight: Use a stack to naturally handle the nested structure, processing inner levels first and bubbling results upward through reversals.
Asked in
Amazon 15 Microsoft 12 Google 8 Facebook 6
23.5K Views
Medium Frequency
~15 min Avg. Time
892 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