# Insert minimum parantheses to make string balanced

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.

**Examples:**

Input:S = 221Output:((22)1)Explanation:

The string ((2))((2))(1) is not valid solutions because it is not of minimum length.

Input:S = 3102Output:(((3))1)0((2))

**Approach:**

- 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.

- Subtract current element from the previous element (int(S[i-1]) – int(S[i])) and store its value in a variable

Below is the implementation of the above approach:

`# Python 3 implementation to balance ` `# the string` ` ` `# Function to insert matching parantheses` `def` `ParanthesesNesting(S):` ` ` ` ` `# To check first element if 0 or not` ` ` `if` `S[` `0` `]` `=` `=` `'0'` `:` ` ` `out ` `=` `'0'` ` ` `p ` `=` `0` ` ` ` ` `else` `:` ` ` `out ` `=` `'('` `*` `(` `int` `(S[` `0` `])) ` `+` `S[` `0` `]` ` ` `p ` `=` `int` `(S[` `0` `])` ` ` ` ` `# Loop from 1 to length of input_string` ` ` `for` `i ` `in` `range` `(` `1` `, (` `len` `(S))):` ` ` `w ` `=` `int` `(S[i ` `-` `1` `]) ` `-` `int` `(S[i])` ` ` ` ` `# To check w is greater than or ` ` ` `# equal to zero or not` ` ` `if` `(w >` `=` `0` `):` ` ` `out ` `=` `out ` `+` `')'` `*` `int` `(w) ` `+` `S[i]` ` ` `p ` `=` `p ` `-` `w` ` ` ` ` `else` `:` ` ` `out ` `=` `out ` `+` `'('` `*` `(` `int` `(S[i]) ` `-` `p) ` `+` `S[i]` ` ` `p ` `=` `int` `(S[i])` ` ` ` ` `y ` `=` `out.count(` `'('` `) ` `-` `out.count(` `')'` `)` ` ` `out ` `+` `=` `')'` `*` `int` `(y)` ` ` `return` `(out)` ` ` `# Driver code ` `if` `__name__ ` `=` `=` `'__main__'` `: ` ` ` `string ` `=` `'221'` ` ` `print` `(ParanthesesNesting(string))` |

**Output:**

((22)1)