Minimum number of bracket reversals to make an expression balanced

Strings (Advanced Algo) Medium Problems Hard
  • Fact: This problem is closely related to the way compilers and interpreters in programming languages such as Python, Java, and C++ check for correct use of parentheses in the source code
  • These tools use similar algorithms to maintain a stack of opening brackets and match them with closing ones, ensuring balanced usage
  • Such algorithms also inform how text editors and IDEs spot parenthesis errors and provide developers with suggestions to fix the errors or autofix them
  • Misuse of parentheses can lead to syntax errors, affecting the proper execution of the code

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