Minimum number of bracket reversals to make an expression balanced

Strings (Advanced Algo) Medium Problems Hard

Given a string s consisting of only opening and closing brackets '(' and ')', find out the minimum number of reversals required to convert the string into a balanced expression.


If it is not possible to make the brackets balanced, return -1. A reversal means changing '(' to ')' or vice-versa.

Examples:

Input: s = ")(())((("


Output: 3


Explanation: One way to balance is:

"((())())". There is no balanced sequence

that can be formed in lesser reversals.

Input: s = "(()((()(())(("


Output: -1


Explanation: There's no way we can balance

this sequence of braces.

Input: s="((())())"

Constraints

  • 1 <= s.length <= 104

Hints

  • "Traverse s, keeping track of opening and closing mismatches. If ( appears without a matching ), it becomes an opening mismatch. If ) appears without a matching (, it becomes a closing mismatch."
  • "If the total number of unmatched brackets is odd, return -1 (odd-length strings can never be balanced). Otherwise, compute the minimum flips"

Company Tags

Red Hat Target Swiggy Docker OYO Rooms Rockstar Games Databricks Qualcomm Alibaba Shopify American Express Ubisoft AMD Freshworks Instacart eBay PwC MongoDB Lyft Goldman Sachs Medtronic GE Healthcare Zynga Electronic Arts Morgan Stanley Google Microsoft Amazon Meta Apple Netflix Adobe