Given a string of digits S. The task is to insert a minimum number of opening and closing parentheses into the string S such that the resulting string is balanced and each digit d must be inside d pairs of matching parentheses.
Input: S = 221
The string ((2))((2))(1) is not valid solutions because it is not of minimum length.
Input: S = 3102
- First, we will insert the required opening parentheses for the first element and store its value in p.
Then we iterate over the string from 1 to length of string and
- Subtract current element from the previous element (int(S[i-1]) – int(S[i])) and store its value in a variable w.
- If w >= 0 then insert w closing parentheses and update p to (p – w). Otherwise,
- Insert current value minus p (int(S[i]) – p) opening parentheses and update p to equals to the current value.
- At the end of the loop, we balance parentheses by inserting the required closing parentheses.
Below is the implementation of the above approach:
- Minimum number of additons to make the string balanced
- Minimum number of bracket reversals needed to make an expression balanced
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Minimum changes required to make first string substring of second string
- Minimum changes to a string to make all substrings distinct
- Minimum number of deletions to make a string palindrome | Set 2
- Minimum cost to make a string free of a subsequence
- Count minimum swap to make string palindrome
- Minimum number of deletions to make a string palindrome
- Minimum replacements in a string to make adjacent characters unequal
- Minimum number of swaps to make two binary string equal
- Minimum operations required to make the string satisfy the given condition
- Minimum swaps required to make a binary string alternating
- Minimum number of Appends needed to make a string palindrome
- Minimum characters to be added at front to make string palindrome
- Minimum number of replacements to make the binary string alternating | Set 2
- Minimum swaps to make two strings equal by swapping only with third string
- Minimum swaps required to make a binary string divisible by 2^k
- Minimum number of swaps required to make the string K periodic
- Minimum number of characters to be removed to make a binary string alternate
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.