Skip to content
Related Articles

Related Articles

Minimize cost to rearrange substrings to convert a string to a Balanced Bracket Sequence
  • Difficulty Level : Hard
  • Last Updated : 28 Jan, 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count minimum number of
// operations to convert the string to
// a balanced bracket sequence
void countMinMoves(string str)
{
    int n = str.size();
 
    // Initialize the integer array
    int a[n] = { 0 };
    int j, ans = 0, i, sum = 0;
 
    // Traverse the string
    for (i = 0; i < n; i++) {
 
        // Decrement a[i]
        if (str[i] == ')') {
            a[i] += sum - 1;
        }
 
        // Increment a[i]
        else {
            a[i] += sum + 1;
        }
 
        // Update the sum as current
        // value of arr[i]
        sum = a[i];
    }
 
    // If answer exists
    if (sum == 0) {
 
        // Traverse from i
        i = 1;
 
        // Find all substrings with 0 sum
        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++;
        }
 
        // Print the sum of sizes
        cout << ans << endl;
    }
 
    // No answer exists
    else
        cout << "-1\n";
}
 
// Driver Code
int main()
{
    string str = ")(()";
    countMinMoves(str);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
class GFG
{
 
  // Function to count minimum number of
  // operations to convert the string to
  // a balanced bracket sequence
  static void countMinMoves(String str)
  {
    int n = str.length();
 
    // Initialize the integer array
    int a[] = new int[n];
    int j, ans = 0, i, sum = 0;
 
    // Traverse the string
    for (i = 0; i < n; i++)
    {
 
      // Decrement a[i]
      if (str.charAt(i) == ')')
      {
        a[i] += sum - 1;
      }
 
      // Increment a[i]
      else
      {
        a[i] += sum + 1;
      }
 
      // Update the sum as current
      // value of arr[i]
      sum = a[i];
    }
 
    // If answer exists
    if (sum == 0)
    {
 
      // Traverse from i
      i = 1;
 
      // Find all substrings with 0 sum
      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++;
      }
 
      // Print the sum of sizes
      System.out.println(ans);
    }
 
    // No answer exists
    else
      System.out.println("-1");
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String str = ")(()";
    countMinMoves(str);
  }
}
 
// This code is contributed by AnkThon

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to count minimum number of
# operations to convert the string to
# a balanced bracket sequence
def countMinMoves(str):
     
    n = len(str)
     
    # Initialize the integer array
    a = [0 for i in range(n)]
    j, ans, sum = 0, 0, 0
 
    # Traverse the string
    for i in range(n):
         
        # Decrement a[i]
        if (str[i] == ')'):
            a[i] += sum - 1
             
        # Increment a[i]
        else:
            a[i] += sum + 1
 
        # Update the sum as current
        # value of arr[i]
        sum = a[i]
 
    # If answer exists
    if (sum == 0):
         
        # Traverse from i
        i = 1
         
        # Find all substrings with 0 sum
        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 the sum of sizes
        print(ans)
 
    # No answer exists
    else:
        print("-1")
 
# Driver Code
if __name__ == '__main__':
     
    str = ")(()"
     
    countMinMoves(str)
 
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
class GFG
{
 
  // Function to count minimum number of
  // operations to convert the string to
  // a balanced bracket sequence
  static void countMinMoves(string str)
  {
    int n = str.Length;
 
    // Initialize the integer array
    int []a = new int[n];
    int j, ans = 0, i, sum = 0;
 
    // Traverse the string
    for (i = 0; i < n; i++)
    {
 
      // Decrement a[i]
      if (str[i] == ')')
      {
        a[i] += sum - 1;
      }
 
      // Increment a[i]
      else
      {
        a[i] += sum + 1;
      }
 
      // Update the sum as current
      // value of arr[i]
      sum = a[i];
    }
 
    // If answer exists
    if (sum == 0)
    {
 
      // Traverse from i
      i = 1;
 
      // Find all substrings with 0 sum
      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++;
      }
 
      // Print the sum of sizes
      Console.WriteLine(ans);
    }
 
    // No answer exists
    else
      Console.WriteLine("-1");
  }
 
  // Driver Code
  public static void Main()
  {
    string str = ")(()";
    countMinMoves(str);
  }
}
 
// This code is contributed by bgangwar59

chevron_right


Output: 

2

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :