Reverse Substrings Between Each Pair of Parentheses

MediumStackstack

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a string s of lowercase letters and **balanced** parentheses. For every matching pair of parentheses, reverse the text enclosed by it, working from the **innermost** pair outward (so text inside nested pairs gets reversed more than once). Return the final string with all parentheses removed. Aim for O(n) time; the straightforward stack solution is O(n^2) in the worst case.

Examples

Input: s = "a(bc)d"
Output: "acbd"
Reverse "bc" to "cb".
Input: s = "(ab(cd)e)"
Output: "ecdba"
The inner pair makes "abdce", then the outer pair reverses it to "ecdba".
Input: s = "(u(love)i)"
Output: "iloveu"
Inner: "uevoli"; outer: "iloveu".

Constraints

  • 1 <= s.length <= 2000
  • s contains only lowercase English letters and '(' and ')'
  • All parentheses in s are balanced

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More stack problems