Problem
Given a parentheses string s
containing only the characters '('
and ')'
.
A parentheses string is balanced if:
- Any left parenthesis
'('
must have a corresponding two consecutive right parenthesis'))'
. - Left parenthesis
'('
must go before the corresponding two consecutive right parenthesis'))'
.
In other words, we treat '('
as an opening parenthesis and '))'
as a
closing parenthesis.
- For example,
"())"
,"())(())))"
and"(())())))"
are balanced,")()"
,"()))"
and"(()))"
are not balanced.
You can insert the characters '('
and ')'
at any position of the string to
balance it if needed.
Return the minimum number of insertions needed to make s
balanced.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= s.length <= 105
s
consists of'('
and')'
only.
Solution
Method 1 – Greedy Counting
Intuition
We need to match every ‘(’ with two consecutive ‘)’. By scanning the string from left to right, we can keep track of how many ‘)’ are needed and how many insertions are required. If we see a ‘(’, we expect two ‘)’ to follow. If we see a ‘)’, we check if it completes a pair or if we need to insert more ‘)’ or ‘(’.
Approach
- Initialize
need
(number of ‘)’ needed) andinsertions
(number of insertions required) to 0. - Iterate through each character in
s
:- If ‘(’, increment
need
by 2. Ifneed
is odd, insert one ‘)’ and decrementneed
by 1. - If ‘)’, decrement
need
by 1. Ifneed
becomes negative, insert one ‘(’, resetneed
to 1.
- If ‘(’, increment
- After processing, add any remaining
need
toinsertions
. - Return
insertions
.
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length ofs
, since we scan the string once. - 🧺 Space complexity:
O(1)
, only constant extra space is used.
Code
|
|
|
|
|
|