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
Wormhole Technique - Reverse Substrings INPUT String s with parentheses ( u ( l o v e ) i ) s = "(u(love)i)" Wormhole Pairs 0 9 Outer pair: 0 --> 9 2 7 Inner pair: 2 --> 7 ALGORITHM STEPS 1 Find Matching Pairs Use stack to pair ( with ) Store pairs as "wormholes" 2 Build Portal Map pair[i] = j means i teleports to j pair[0]=9, pair[9]=0, etc. 3 Traverse with Direction Start: i=0, direction=+1 (right) At '(': jump, reverse direction 4 Collect Characters Skip parentheses Add letters to result Wormhole Traversal: 0--(jump)-->9, dir=-1 9-->8(i)-->7--(jump)-->2 2-->3(l)4(o)5(v)6(e)-->end FINAL RESULT Traversal path produces: i l o v e u iloveu OK - No parentheses! Wormhole Path ( ) teleport! i ... Direction flips at each parenthesis = auto-reverse! Key Insight: The Wormhole Technique creates "portals" between matching parentheses. When traversing hits a parenthesis, it teleports to its pair AND reverses direction. This automatically handles nested reversals in O(n) time without actually reversing substrings - the direction change naturally produces the reversed output! TutorialsPoint - Reverse Substrings Between Each Pair of Parentheses | Wormhole Technique
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