Problem Description
Given a string s consisting only of '(' and ')', balance the string by ensuring every '(' has a matching pair of consecutive '))'. You are allowed to insert '(' or ')' anywhere in the string. The task is to determine the minimum number of insertions required to make the string balanced.
Key Insights
- Every '(' expects exactly two ')' to be balanced.
- Process the string with a single pass, maintaining the count of required ')' characters.
- When encountering a ')', check if it forms a consecutive pair. If not, a missing ')' may need to be inserted.
- If extra ')' are found without a matching '(', insert a '('.
- Greedily handle the unmatched parentheses while iterating through the string.
Space and Time Complexity
Time Complexity: O(n), where n is the length of s as we traverse the string once.
Space Complexity: O(1), using only a few integer variables for counting.
Solution
We use a greedy approach with a counter (needed) that indicates how many ')' characters are required to balance the string so far. As we iterate:
- When a '(' is encountered, increment the needed count by 2.
- When a ')' is encountered:
- If it is the start of a pair, decrement the needed count by 2.
- If a single ')' is encountered (i.e., the next character is not ')' or we are at the end), we assume one is missing and adjust the counter accordingly (and count an insertion).
- If needed becomes negative at any point, it means there are extra ')' so we insert a '(' and adjust.
- At the end, any remaining needed value implies missing ')' which are added as insertions.
Key tricks:
- Ensure that when a needed count goes negative, we immediately fix it by inserting a '('.
- Carefully check pairs of consecutive ')' to determine if they form valid closing pairs.