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: