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 “)”.
Input: str = “)(()“
Choose substring S[0, 1] ( = “)(“ ) and rearrange it to “()”. Cost = 2.
Now, the string modifies to S = “()()”, which is balanced.
Input: S = “()))”
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:
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.