Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimum number of alternate subsequences required to be removed to empty a Binary String
Next article icon

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

Last Updated : 31 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
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)



Next Article
Minimum number of alternate subsequences required to be removed to empty a Binary String
author
sanachaitali30
Improve
Article Tags :
  • Arrays
  • C++
  • C++ Programs
  • DSA
  • Strings
  • substring
Practice Tags :
  • CPP
  • Arrays
  • Strings

Similar Reads

  • C++ Program to Minimize characters to be changed to make the left and right rotation of a string same
    Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc
    3 min read
  • Minimum number of alternate subsequences required to be removed to empty a Binary String
    Given a binary string S consisting of N characters, the task is to print the minimum number of operations required to remove all the characters from the given string S by removing a single character or removing any subsequence of alternate characters in each operation. Examples: Input: S = "010101"O
    6 min read
  • Convert given string to another by minimum replacements of subsequences by its smallest character
    Given two strings A and B, the task is to count the minimum number of operations required to convert the string A to B. In one operation, select a subsequence from string A and convert every character of that subsequence to the smallest character present in it. If it is not possible to transform, th
    10 min read
  • C++ Program for Minimum move to end operations to make all strings equal
    Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.Examples: Input : n = 2 arr[] = {"molzv", "lzvmo"} Output : 2 Explanation: In first string, we remove first element("m") from first
    3 min read
  • Lexicographically smallest permutation of a string that contains all substrings of another string
    Given two strings A and B, the task is to find lexicographically the smallest permutation of string B such that it contains every substring from the string A as its substring. Print “-1” if no such valid arrangement is possible.Examples: Input: A = "aa", B = "ababab" Output: aaabbb Explanation: All
    10 min read
  • Reduce the string to minimum length with the given operation
    Given a string str consisting of lowercase and uppercase characters, the task is to find the minimum possible length the string can be reduced to after performing the given operation any number of times. In a single operation, any two consecutive characters can be removed if they represent the same
    6 min read
  • C++ Program for Minimum rotations required to get the same string
    Given a string, we need to find the minimum number of rotations required to get the same string. Examples: Input : s = "geeks" Output : 5 Input : s = "aaaa" Output : 1 The idea is based on below post.A Program to check if strings are rotations of each other or not Step 1: Initialize result = 0 (Here
    2 min read
  • C++ Program to Find Lexicographically minimum string rotation | Set 1
    Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.Source: Google Written TestMore Examples:  Input: GEEKSQUIZ Output: EEKSQUIZG Input: GFG Output: FGG Input: GEEKSFORGEEKS Output: EEKSFORGEEKSG Following is a simple sol
    2 min read
  • Minimize count of flips required such that no substring of 0s have length exceeding K
    Given a binary string str of length N and an integer K where K is in the range (1 ? K ? N), the task is to find the minimum number of flips( conversion of 0s to 1 or vice versa) required to be performed on the given string such that the resulting string does not contain K or more zeros together. Exa
    6 min read
  • Longest subsequence possible that starts and ends with 1 and filled with 0 in the middle
    Given a binary string s, the task is to find the length of the longest subsequence that can be divided into three substrings such that the first and third substrings are either empty or filled with 1 and the substring at the middle is either empty or filled with 0. Examples: Input: s = "1001" Output
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences