Parenthesis are said to be balanced when every opening brace has a closing brace like “()()” or “(())” or “(()())” etc. Incorrect balancing includes “)(” or “))((” etc. The task here is to correct the sequence of parenthesis in such a way that it is done in minimum cost. And shifting of parenthesis by over one parentheses costs 1. If the parenthesis can’t be balanced then print -1.
Input : ()
Output : 0
Explanation : Already balanced
Input : ))((
Output : 4
Explanation : Firstly, ) at position 1st goes to the last position, costing 3, so we get )((). Then, ) at position 1st goes to the 2nd position costing 1. So, finally we get ()(). Therefore, the total cost is 4.
- Store the braces in string.
- Run a loop to string size to store the count of opening and closing braces.
- Check if number of opening brace is equal to number of closing brace or not.
- If the braces are not equal then print -1 depicting that the string cant be balanced. Else proceed further.
- Initially, Check at 0th index that whether the string contains opening brace or closing brace. If we get an opening brace then store +1 in the array at index 0, else if closing brace is present then place -1 at 0th index.
- Now run a loop from 1st index to array length.
- If opening brace is present at index i then add +1 to value at previous index i.e. i-1 and store sum at index i.
- If closing brace is present at index i then add -1 to value at previous index i.e. i-1 and store sum at index i.
- If value at index i is negative i.e less than 0, then add the absolute value of array[i] into a variable(ans in below program).
Below is the implementation of above approach :
- Count pairs of parentheses sequences such that parentheses are balanced
- Balance a string after removing extra brackets
- Check for balanced parentheses in an expression
- Check for balanced parentheses in Python
- Length of longest balanced parentheses prefix
- Check for balanced parentheses in an expression | O(1) space
- Minimum number of Parentheses to be added to make it valid
- Check for balanced parentheses in an expression | O(1) space | O(N^2) time complexity
- Minimum cost to modify a string
- Cost to make a string Panagram
- Cost to make a string Panagram | Set 2
- Minimum cost to make two strings same
- Minimum cost to construct a string
- Minimum Cost To Make Two Strings Identical
- Minimum cost to convert string into palindrome
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.