The Wayback Machine - https://web.archive.org/web/20240717024553/https://www.geeksforgeeks.org/minimize-cost-to-rearrange-substrings-to-convert-a-string-to-a-balanced-bracket-sequence/
Open In App

Minimize cost to rearrange substrings to convert a string to a Balanced Bracket Sequence

Last Updated : 31 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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;
}


Java




// 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


Python3




# 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


C#




// 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


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to count minimum number of
// operations to convert the string to
// a balanced bracket sequence
function countMinMoves(str)
{
    var n = str.length;
 
    // Initialize the integer array
    var a = Array(n).fill(0);
    var 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
        document.write( ans + "<br>");
    }
 
    // No answer exists
    else
        document.write( "-1<br>");
}
 
// Driver Code
var str = ")(()";
countMinMoves(str);
 
</script>


Output: 

2

 

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



Similar Reads

Check if the bracket sequence can be balanced with at most one change in the position of a bracket
Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "(())"Input: str = "()))(()" Output: No Approach: Co
6 min read
Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Set 2
Given a bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "(())"Input: str = "()))(()" Output: No Approach: The problem ca
5 min read
Convert an unbalanced bracket sequence to a balanced sequence
Given an unbalanced bracket sequence of '(' and ')', convert it into a balanced sequence by adding the minimum number of '(' at the beginning of the string and ')' at the end of the string. Examples: Input: str = ")))()" Output: "((()))()" Input: str = "())())(())())" Output: "(((())())(())())" Method 1: Approach: Initialize an empty stack.Iterate
13 min read
Minimum Cost required to generate a balanced Bracket Sequence
Given a string str of length N, representing a bracket sequence, and two integers A and B, the task is to find the minimum cost required to obtain a regular bracket sequence from str by performing any number of moves(possibly zero) of the following types: Remove a character from the string for a cost A.Remove a character from the string and append
9 min read
Maximum Pairs of Bracket Sequences which can be concatenated to form a Regular Bracket Sequence
Given an array arr[] of N strings such that each string consists of characters '(' and ')', the task is to find the maximum number of pairs of strings such that the concatenation of the two strings is a Regular Bracket Sequence. A Regular Bracket Sequence is a string consisting of brackets '(' and ')' such that every prefix from the beginning of th
9 min read
Check if a given string can be converted to a Balanced Bracket Sequence
Given a string S of size N consisting of '(', ')', and '$', the task is to check whether the given string can be converted into a balanced bracket sequence by replacing every occurrence of $ with either ) or (. A balanced bracket sequence is a sequence where every opening bracket "(" has a corresponding closing bracket ")". Examples: Input: S = "()
12 min read
Find the lexicographical next balanced bracket sequence
Given a balanced bracket sequence as a string str containing character '(' or ')', the task is to find the next lexicographical order balanced sequence if possible else print -1.Examples: Input: str = "(())" Output: ()()Input: str = "((()))" Output: (()()) Approach: First find the rightmost opening bracket which we can replace it by a closing brack
6 min read
Find index of closing bracket for a given opening bracket in an expression
Given a string with brackets. If the start index of the open bracket is given, find the index of the closing bracket. Examples: Input : string = [ABC[23]][89] index = 0 Output : 8 The opening bracket at index 0 corresponds to closing bracket at index 8.Recommended PracticeClosing bracket indexTry It! The idea is to use Stack data structure. We trav
7 min read
Minimize cost to convert given string into concatenation of equal substrings of length K
Given a string S of length N consisting of lowercase letters and an integer K, where N % K = 0, the task is to find the minimum cost to convert the given string into a concatenated string of the same K-length substrings by performing the following operations: A character can be replaced with another character.The cost of each operation is the absol
8 min read
Number of balanced bracket expressions that can be formed from a string
Given a string str comprising of characters (, ), {, }, [, ] and ?. The task is to find the total number of balanced bracket expressions formed when ? can be replaced with any of the bracket characters. Here are some examples of balanced bracket expressions: {([])}, {()}[{}] etc. And, unbalanced bracket expressions: {[}, {()], {()}[) etc. Examples:
12 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg