Minimize cost to rearrange substrings to convert a string to a Balanced Bracket Sequence
Last Updated :
31 May, 2021
Given a string S of length N consisting of characters “(“ and “)” only, the task is to convert the given string into a balanced parenthesis sequence by selecting any substring from the given string S and reorder the characters of that substring. Considering length of each substring to be the cost of each operation, minimize the total cost required.
A string is called balanced if every opening parenthesis “(” has a corresponding closing parenthesis “)”.
Examples:
Input: str = “)(()“
Output: 2
Explanation:
Choose substring S[0, 1] ( = “)(“ ) and rearrange it to “()”. Cost = 2.
Now, the string modifies to S = “()()”, which is balanced.
Input: S = “()))”
Output: -1
Approach: The idea is to first check if the string can be balanced or not i.e., count the number of open and closed parenthesis and if they are unequal, then print -1. Otherwise, follow the steps below to find the total minimum cost:
- Initialize an array arr[] of length N.
- Initialize sum as 0 to update the array elements with the values sum.
- Traverse the given string from i = 0 to N – 1 and perform the following steps:
- If the current character is “(“, then update arr[i] as (sum + 1). Otherwise, update arr[i] as (sum – 1).
- Update the value of sum as arr[i].
- After completing the above steps, if the value of arr[N – 1] is non-zero then string can’t be balanced and print “-1”.
- If the string can be balanced, then print the sum of sizes of disjoint subarray having sum 0 as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void countMinMoves(string str)
{
int n = str.size();
int a[n] = { 0 };
int j, ans = 0, i, sum = 0;
for (i = 0; i < n; i++) {
if (str[i] == ')' ) {
a[i] += sum - 1;
}
else {
a[i] += sum + 1;
}
sum = a[i];
}
if (sum == 0) {
i = 1;
while (i < n) {
j = i - 1;
while (i < n && a[i] != 0)
i++;
if (i < n && a[i - 1] < 0) {
ans += i - j;
if (j == 0)
ans++;
}
i++;
}
cout << ans << endl;
}
else
cout << "-1\n" ;
}
int main()
{
string str = ")(()" ;
countMinMoves(str);
return 0;
}
|
Java
class GFG
{
static void countMinMoves(String str)
{
int n = str.length();
int a[] = new int [n];
int j, ans = 0 , i, sum = 0 ;
for (i = 0 ; i < n; i++)
{
if (str.charAt(i) == ')' )
{
a[i] += sum - 1 ;
}
else
{
a[i] += sum + 1 ;
}
sum = a[i];
}
if (sum == 0 )
{
i = 1 ;
while (i < n)
{
j = i - 1 ;
while (i < n && a[i] != 0 )
i++;
if (i < n && a[i - 1 ] < 0 )
{
ans += i - j;
if (j == 0 )
ans++;
}
i++;
}
System.out.println(ans);
}
else
System.out.println( "-1" );
}
public static void main(String[] args)
{
String str = ")(()" ;
countMinMoves(str);
}
}
|
Python3
def countMinMoves( str ):
n = len ( str )
a = [ 0 for i in range (n)]
j, ans, sum = 0 , 0 , 0
for i in range (n):
if ( str [i] = = ')' ):
a[i] + = sum - 1
else :
a[i] + = sum + 1
sum = a[i]
if ( sum = = 0 ):
i = 1
while (i < n):
j = i - 1
while (i < n and a[i] ! = 0 ):
i + = 1
if (i < n and a[i - 1 ] < 0 ):
ans + = i - j
if (j = = 0 ):
ans + = 1
i + = 1
print (ans)
else :
print ( "-1" )
if __name__ = = '__main__' :
str = ")(()"
countMinMoves( str )
|
C#
using System;
class GFG
{
static void countMinMoves( string str)
{
int n = str.Length;
int []a = new int [n];
int j, ans = 0, i, sum = 0;
for (i = 0; i < n; i++)
{
if (str[i] == ')' )
{
a[i] += sum - 1;
}
else
{
a[i] += sum + 1;
}
sum = a[i];
}
if (sum == 0)
{
i = 1;
while (i < n)
{
j = i - 1;
while (i < n && a[i] != 0)
i++;
if (i < n && a[i - 1] < 0)
{
ans += i - j;
if (j == 0)
ans++;
}
i++;
}
Console.WriteLine(ans);
}
else
Console.WriteLine( "-1" );
}
public static void Main()
{
string str = ")(()" ;
countMinMoves(str);
}
}
|
Javascript
<script>
function countMinMoves(str)
{
var n = str.length;
var a = Array(n).fill(0);
var j, ans = 0, i, sum = 0;
for (i = 0; i < n; i++) {
if (str[i] == ')' ) {
a[i] += sum - 1;
}
else {
a[i] += sum + 1;
}
sum = a[i];
}
if (sum == 0) {
i = 1;
while (i < n) {
j = i - 1;
while (i < n && a[i] != 0)
i++;
if (i < n && a[i - 1] < 0) {
ans += i - j;
if (j == 0)
ans++;
}
i++;
}
document.write( ans + "<br>" );
}
else
document.write( "-1<br>" );
}
var str = ")(()" ;
countMinMoves(str);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...