1541. Minimum Insertions to Balance a Parentheses String
1. Description
Given a string s made of ‘(’ and ‘)’, balance it using a special matching rule: each ‘(’ needs a matching pair of consecutive ‘)’ characters appearing after it. Thus, ‘))’ acts as a single closing unit.
You may insert either character anywhere in s, including at the beginning or end. Return the fewest insertions required to balance the string.
2. Example
Example 1
Input: s = “(()))”
Output: 1
Explanation: Appending ‘)’ produces “(())))”, which satisfies the matching rule.
Example 2
Input: s = “())”
Output: 0
Explanation: No insertions are needed.
Example 3
Input: s = “))())(”
Output: 3
Explanation: Insert ‘(’ at the beginning and append ‘))’ at the end.
3. Constraints
- 1 <= s.length <= $10^5$
- Each character of s is either ‘(’ or ‘)’.
4. Solutions
Greedy
n = str.size()
Time complexity: O(n)
Space complexity: O(1)
| |