Problem · String
Balancing Parentheses
Learn this problemProblem statement
Given a string that consists of left and right parentheses, '(' and ')', balance the parentheses by inserting parentheses as necessary. Determine the minimum number of characters that must be inserted.
Function
balanceParentheses(s: String) → int
Complete the function balanceParentheses in the editor.
balanceParentheses has the following parameter:
String s: a string of parentheses
Returns
int: the minimum number of insertions needed
♫⋆。♪ ₊˚♬ ゚.Huge Thanks to spike!!𓂃 🐳𓈒𓏸
Examples
Example 1
s = "()))"return = 2Insert a '(' 2 times at the beginning of the string to make it valid: '((()))'
Example 2
s = "))(("return = 4Insert 2 left parentheses at the start and 2 right parentheses at the end of the string to get "(()))(())" after 4 insertions.
Example 3
s = "(()))"return = 1Insert 1 left paranthesis at the left end of the string to get '((()))'. The string is balanced after 1 insertion.
Example 4
s = "()()"return = 0The sequence is already valid.
Constraints
1 ≤ length of s ≤ 105
More Oracle problems
- Alphabetically Maximum SubstringPHONE SCREEN · Seen Jul 2026
- Best Time to Buy and Sell StockPHONE SCREEN · ONSITE INTERVIEW · Seen Jul 2026
- Enumerate Right-and-Down Matrix PathsONSITE INTERVIEW · Seen Jul 2026
- Maximize Movie Ratings Without Consecutive SkipsONSITE INTERVIEW · Seen Jul 2026
- Add One to a Number Represented as DigitsONSITE INTERVIEW · Seen Jul 2026
- Top K Frequent Elements with Larger-Value Tie BreakONSITE INTERVIEW · Seen Jul 2026
- Merge k Sorted ListsPHONE SCREEN · Seen Jul 2026
- Implement a Queue Using Two StacksPHONE SCREEN · Seen Jul 2026