Minimum Insertions to Balance a Parentheses String Problem
Description
LeetCode Problem 1541.
You are given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if it can be formed using the following rules:
- The empty string is balanced.
- If
Ais balanced, then'('+A+'))'is balanced. - If
AandBare balanced, then their concatenation is balanced.
In other words, every left parenthesis '(' must have a corresponding pair of two consecutive right parentheses '))' that comes after it, and every right parenthesis must belong to exactly one such matching pair.
For example, "())", "())(())))" and "(())())))" are balanced, while ")()", "()))" and "(()))" are not balanced.
You can insert the characters '(' and ')' at any position of the string to balance it if needed.
Return the minimum number of insertions needed to make s balanced.
Example 1:
Input: s = "(()))"
Output: 1
Explanation:
The second '(' is matched with two consecutive ')', but the first '(' has only one matching ')'. We need to insert one more ')' at the end to make the string "(())))", which is balanced.
Example 2:
Input: s = "())"
Output: 0
Explanation:
The string is already balanced because its '(' is followed by two consecutive ')', and both right parentheses belong to that matching pair.
Example 3:
Input: s = "))())("
Output: 3
Explanation:
Insert '(' at the beginning to match the first '))', and insert '))' at the end to match the last '('. Three insertions are needed in total.
Constraints:
1 <= s.length <= 10^5sconsists of'('and')'only.
Solution
Approach: Greedy Scan with Open Count
Here a '(' is closed by two consecutive ')', so we read the string in units: a '(', or a "))". Keep open, the number of '(' still waiting to be closed, and inserted, the number of characters we had to add.
- On
'(', increaseopen. - On
')': if the next character is also')', the two form a"))"and we skip both. If not, a lone')'can only become"))"by inserting another')'right after it, so add one toinserted. Then this"))"closes a waiting'('ifopen > 0. Otherwise no'('is available, and we must insert one before it. - At the end, each of the
openleftover'('needs"))", so add2 * open.
The tricky part is not to count the right parentheses one by one. In ")()", the first ')' and the second are not consecutive, so they cannot form a pair: the first one needs a '(' and a ')' inserted, and the "()" that follows needs one more ')', three insertions in all. Fixing each lone ')' on the spot, and matching each "))" with the latest waiting '(', is always optimal, since an insertion made now can never be saved by anything later.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minInsertions(self, s: str) -> int:
inserted = 0
open_count = 0 # '(' still waiting for their "))"
i, n = 0, len(s)
while i < n:
if s[i] == '(':
open_count += 1
i += 1
continue
# A ')' must come as "))": if the next character is not ')', insert one.
if i + 1 < n and s[i + 1] == ')':
i += 2
else:
inserted += 1
i += 1
# This "))" closes a waiting '(' or needs a new '(' inserted before it.
if open_count > 0:
open_count -= 1
else:
inserted += 1
return inserted + 2 * open_count # every leftover '(' needs "))"