Solution Review: Reverse Parentheses

Let's discuss in detail the solution for the reverse parentheses problem.

Solution

  • We donā€™t need to flip the balanced parentheses, so we remove them first. If all the balanced parentheses are removed, weā€™ll be left with the parentheses of the form )))((((.

  • Letā€™s name the total number of open parenthesis as OpenCount and the total number of closed parenthesis as CloseCount.

  • When OpenCount is even, then CloseCount is also even. Their half-element reversal will make the expression balanced.

  • When OpenCount is odd and CloseCount iis also odd, we have to perform OpenCount/2 and CloseCount/2 reversals. Weā€™ll be left with )(, which needs 2 more reversals. The formula is derived from this:

    • TotalTotal numbernumber ofof reversalsreversals = math.ceil(OpenCount/2)+math.ceil(CloseCount/2)math.ceil (OpenCount / 2) + math.ceil(CloseCount / 2).

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.