
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Insertions to Balance a Parentheses String Using Python
Suppose we have a string s with opening and closing parenthesis '(' and ')'. We can say a parentheses string is balanced when −
Any left parenthesis '(' have a corresponding two consecutive right parenthesis '))'.
A Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.
So for example, "())", "())(())))" are balanced but ")()", "()))" are not. If we have such string, we have to count number of parenthesis (opening or closing) to make string balanced.
So, if the input is like s = "(())))))", then the output will be 1 because if we split it up, we can get "( ()) )) ))", so we need one left parenthesis to make the string "( ()) ()) ))" to make it balanced.
To solve this, we will follow these steps −
:= 0, n := size of s
ret := 0, i := 0
-
while i < n, do
if s[i] is same as '(', then
-
:= o + 1
-
otherwise,
-
if i + 1 < n and s[i + 1] is same as ')', then
-
if o is 0, then
ret := ret + 1
otherwise,
-
-
-
-
:= o - 1
i := i + 1
-
otherwise,
ret := ret + 1
-
if o is 0, then
ret := ret + 1
otherwise,
-
:= o - 1
i := i + 1
return ret + 2 * o
Let us see the following implementation to get better understanding −
Example
def solve(s): o = 0 n = len(s) ret = 0 i = 0 while i < n: if s[i] == '(': o += 1 else: if i + 1 < n and s[i + 1] == ')': if not o: ret += 1 else: o -= 1 i += 1 else: ret += 1 if not o: ret += 1 else: o -= 1 i += 1 return ret + 2 * o s = "(())))))" print(solve(s))
Input
"(())))))"
Output
3