Minimum Insertions to Balance a Parentheses String - Problem
The Balance Challenge
Imagine you're working with a special parentheses system where the rules are slightly different from traditional parentheses. In this system:
- Every opening parenthesis
'('must be matched with exactly two consecutive closing parentheses'))' - The opening parenthesis must come before its matching closing pair
Examples of balanced strings:
"())"- One opening, two closing"())(()))"- Two complete pairs"(())()))"- Nested and sequential pairs
Examples of unbalanced strings:
")()"- Closing before opening"()))"- Missing opening parenthesis"(()))"- Missing one closing parenthesis
Your task is to find the minimum number of insertions needed to make any given parentheses string balanced according to these rules.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "())"
โบ
Output:
1
๐ก Note:
We have one '(' that needs to be matched with '))', but we only have one ')'. We need to insert one more ')' at the end to make it "()))" which is balanced.
example_2.py โ Multiple Pairs
$
Input:
s = "((("
โบ
Output:
6
๐ก Note:
We have three unmatched '(' characters. Each needs to be matched with '))', so we need to insert 3 ร 2 = 6 closing parentheses to get "((())))"
example_3.py โ Mixed Case
$
Input:
s = "()))"
โบ
Output:
1
๐ก Note:
The first ')' doesn't have a matching '(' before it, and the ')))' forms one valid pair. We need to insert one '(' at the beginning to make "(()))" which is balanced.
Constraints
- 1 โค s.length โค 105
- s consists of '(' and ')' only
- Each '(' must be matched with exactly two consecutive ')'
Visualization
Tap to expand
Understanding the Visualization
1
Collect Locks
When we see '(', we add it to our collection of unmatched locks
2
Use Key Pairs
When we see '))', we try to use it to open a lock from our collection
3
Handle Single Keys
When we see single ')', we need to get another key and then use the pair
4
Final Matching
Any remaining locks need their key pairs manufactured
Key Takeaway
๐ฏ Key Insight: By processing characters from left to right and maintaining a count of unmatched opening parentheses, we can determine the minimum insertions needed in a single pass. The greedy approach works because we can always make locally optimal decisions about when to match or insert parentheses.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code