Description
Solutions
Balancing Parentheses
π₯ FULLTIMEπRELATED PROBLEMS
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 Description
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
β«βqβͺ βΛβ¬ οΎ.Huge Thanks to spike!!π π³ππΈ
Example 1:
Input: s = "()))"
Output: 2
Explanation:Insert a '(' 2 times at the beginning of the string to make it valid: '((()))'
Example 2:
Input: s = "))(("
Output: 4
Explanation:Insert 2 left parentheses at the start and 2 right parentheses at the end of the string to get "(()))(())" after 4 insertions.
Example 3:
Input: s = "(()))"
Output: 1
Explanation:Insert 1 left paranthesis at the left end of the string to get '((()))'. The string is balanced after 1 insertion.
Example 4:
Input: s = "()()"
Output: 0
Explanation:The sequence is already valid.
Constraints:
1 β€ length of s
β€ 105

Related Problems
Testcase
Result
Case 1
input:
output: