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.
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="((())())"
To find the minimum number of bracket reversals to make an expression balanced, firstly the number of balanced brackets must be found. Ignoring the balanced brackets, it will become easier to understand the required count.
")(())((("
")((("
open
and number of closed brackets are represented as close
, it can be seen that the minimum number of bracket reversals to make an expression balanced will depend upon:
(open / 2) + (open % 2) + (close / 2) + (close % 2)where
open
and close
represent the number of invalid open and close brackets respectively.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to find the minimum number of reversals required
to convert the string into a balanced expression. */
int countRev(string s) {
int n = s.length(); // Size of string
/* If string is of odd length, it is not
possible to balance the paranthesis */
if(n % 2) return -1;
// To store the count of opening and closing brackets
int open = 0, close = 0;
for(int i=0; i < n; i++) {
// Increment open count if opening bracket is found
if(s[i] == '(') open++;
// Else (closing bracket is found)
else {
/* If a opening bracket is there, a pair
of balanced paranthesis is formed */
if(open > 0) open--;
// Otherwise the closing bracket remain unbalanced
else close++;
}
}
// Computing the result
int ans = (open / 2) + (open % 2) + (close / 2) + (close % 2)
return ans; // Return the result
}
};
int main(){
string s = ")(())(((";
// Creating an instance of Solution class
Solution sol;
/* Function call to find the minimum number of reversals
required to convert the string into a balanced expression. */
int ans = sol.countRev(s);
// Output
cout << "The minimum number of reversals required are: " << ans << endl;
}
import java.util.*;
class Solution {
/* Function to find the minimum number of reversals required
to convert the string into a balanced expression. */
public int countRev(String s) {
int n = s.length(); // Size of string
/* If string is of odd length, it is not
possible to balance the paranthesis */
if(n % 2 != 0) return -1;
// To store the count of opening and closing brackets
int open = 0, close = 0;
for(int i=0; i < n; i++) {
// Increment open count if opening bracket is found
if(s.charAt(i) == '(') open++;
// Else (closing bracket is found)
else {
/* If a opening bracket is there, a pair
of balanced paranthesis is formed */
if(open > 0) open--;
// Otherwise the closing bracket remain unbalanced
else close++;
}
}
// Computing the result
int ans = (open / 2) + (open % 2) + (close / 2) + (close % 2);
return ans; // Return the result
}
}
class Main {
public static void main(String[] args) {
String s = ")(())(((";
// Creating an instance of Solution class
Solution sol = new Solution();
/* Function call to find the minimum number of reversals
required to convert the string into a balanced expression. */
int ans = sol.countRev(s);
// Output
System.out.println("The minimum number of reversals required are: " + ans);
}
}
class Solution:
# Function to find the minimum number of reversals required
# to convert the string into a balanced expression.
def countRev(self, s: str) -> int:
n = len(s) # Size of string
# If string is of odd length, it is not
# possible to balance the paranthesis
if n % 2 != 0:
return -1
# To store the count of opening and closing brackets
open = 0
close = 0
for i in range(n):
# Increment open count if opening bracket is found
if s[i] == '(':
open += 1
# Else (closing bracket is found)
else:
# If a opening bracket is there, a pair
# of balanced paranthesis is formed
if open > 0:
open -= 1
# Otherwise the closing bracket remain unbalanced
else:
close += 1
# Computing the result
ans = (open // 2) + (open % 2) + (close // 2) + (close % 2)
return ans # Return the result
if __name__ == "__main__":
s = ")(())((("
# Creating an instance of Solution class
sol = Solution()
# Function call to find the minimum number of reversals
# required to convert the string into a balanced expression.
ans = sol.countRev(s)
# Output
print("The minimum number of reversals required are:", ans)
class Solution {
/* Function to find the minimum number of reversals required
to convert the string into a balanced expression. */
countRev(s) {
let n = s.length; // Size of string
/* If string is of odd length, it is not
possible to balance the paranthesis */
if (n % 2 !== 0) return -1;
// To store the count of opening and closing brackets
let open = 0, close = 0;
for (let i = 0; i < n; i++) {
// Increment open count if opening bracket is found
if (s[i] === '(') open++;
// Else (closing bracket is found)
else {
/* If a opening bracket is there, a pair
of balanced paranthesis is formed */
if (open > 0) open--;
// Otherwise the closing bracket remain unbalanced
else close++;
}
}
// Computing the result
let ans = Math.floor(open / 2) + (open % 2) + Math.floor(close / 2) + (close % 2);
return ans; // Return the result
}
}
const s = ")(())(((";
// Creating an instance of Solution class
const sol = new Solution();
/* Function call to find the minimum number of reversals
required to convert the string into a balanced expression. */
const ans = sol.countRev(s);
// Output
console.log("The minimum number of reversals required are:", ans);
Time Complexity: O(n) (where n is the length of the input string)
The input string is traversed once taking O(n) time.
Space Complexity: O(1)
Only a couple of variables are used taking constant space.
Q: Does the order of brackets affect reversibility?
A: Yes, the order determines whether mismatches exist. The stack-based approach helps count unbalanced parts correctly.
Q: Why is it impossible to balance an odd-length string?
A: A balanced string must contain an equal number of ( and ). If the length is odd, one bracket will always remain unmatched.
Q: How would the solution change if {} and [] brackets were included?
A: The approach would be extended to track multiple bracket types, ensuring separate counts for {}, [], and ().
Q: How does this compare to other bracket balancing problems, like finding redundant parentheses?
A: This problem focuses on reversal-based correction, whereas redundant parentheses problems focus on removing excess brackets.