Problem
A parentheses string is valid if and only if:
- It is the empty string,
- It can be written as
AB
(A
concatenated withB
), whereA
andB
are valid strings, or - It can be written as
(A)
, whereA
is a valid string.
You are given a parentheses string s
. In one move, you can insert a parenthesis at any position of the string.
- For example, if
s = "()))"
, you can insert an opening parenthesis to be"(()))"
or a closing parenthesis to be"())))"
.
Return the minimum number of moves required to make s
valid.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Video explanation
Here is the video explaining below methods in detail. Please check it out:
Method 1 - Using Stack
Loop through the input array, and initialize the stack and left counter signifying number of left parenthesis required:.
- If we encounter ‘(’, push ‘(’ into stack;
- otherwise, ‘)’, check if there is a matching ‘(’ on top of stack; if no, increase the left counter by 1; if yes, pop it out;
- after the loop, count in the un-matched characters remaining in the stack.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the strings
, because we process each character exactly once. - 🧺 Space complexity:
O(n)
Method 2 - Track left and right bracket needed
Here is the approach:
-
Understanding Valid Parentheses:
- A valid parentheses string must balance every opening parenthesis
'('
with a closing parenthesis')'
.
- A valid parentheses string must balance every opening parenthesis
-
Count Imbalance:
- Traverse the string
s
, maintaining a count of open and close braces. - An imbalance occurs when there are more closing parentheses
')'
than opening parentheses'('
at any point.
- Traverse the string
-
Calculate Minimum Moves:
- Use a counter to track the number of moves to balance open and close parentheses.
- As you traverse the string:
- If a mismatch is detected (more
')'
than'('
), increment the counter. - At the end of traversal, the count of unbalanced opening parentheses also needs to be accounted for in the result.
- If a mismatch is detected (more
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, because we process each character exactly once. - 🧺 Space complexity:
O(1)
- , since we use a few additional variables to keep track of the counters for the needed parentheses, and no additional data structures are used.