Reverse Substrings Between Each Pair of Parentheses

You are given a string `s` of lowercase English letters and brackets. Reverse the strings inside each pair of matching parentheses, starting from the innermost one. The result should not contain any brackets.

30:00

Reverse Substrings Between Each Pair of Parentheses
medium
Free written solution
Topics
Companies

You are given a string s of lowercase English letters and brackets. Reverse the strings inside each pair of matching parentheses, starting from the innermost one. The result should not contain any brackets.

Example 1:
Input: {"s":"(abcd)"}
Output: dcba
Constraints:
  • 1≤s.length≤20001 \leq \text{s.length} \leq 2000

  • s only contains lowercase English characters and parentheses.

  • It is guaranteed that all parentheses are balanced.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"(abcd)"}

First pass: pair every '(' with its ')' using a stack, so the walk can jump between them.

s

(

0

a

1

b

2

c

3

d

4

)

5

Both ends of a pair share a color; ~k names the partner index. Hitting a bracket jumps to its partner and reverses direction.

stack of open '(' indices

empty

output (letters in the order the walker meets them)

filled during the walk
Variables
VariableValue
i-1
d1
res""
DepthFunction Call
Stack empty
0/10