Reverse every substring enclosed by matching parentheses, then remove the parentheses from the final result.
Reverse Substrings Between Each Pair of Parentheses
gfgYou are given a string s consisting of lowercase English letters and parentheses ( and ).
Process the string by repeatedly finding any matching pair of parentheses, reversing the substring inside that pair, and removing the parentheses themselves. Nested parentheses should be handled correctly, so inner reversals affect the text that outer pairs later reverse.
Return the final string after all parentheses have been removed and all reversals have been applied.
s.s contains lowercase letters and the characters ( and ).1 <= s.length.s contains only lowercase letters and parentheses.Example 1
Input
s = "(abcd)"
Output
"dcba"
Explanation
The only parenthesized substring is abcd, which becomes dcba after reversal.
Example 2
Input
s = "(u(love)i)"
Output
"iloveu"
Explanation
First reverse love to get ove l in the inner segment effect, then reverse the outer segment to obtain iloveu after removing parentheses.
Example 3
Input
s = "a(bcdefghijkl(mno)p)q"
Output
"apmnolkjihgfedcbq"
Explanation
The inner substring mno becomes onm, and then the larger parenthesized section is reversed with that transformed content.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.