Minimum Add to Make Parentheses Valid
LeetCode 957 | Difficulty: Mediumβ
MediumProblem Descriptionβ
A parentheses string is valid if and only if:
- It is the empty string,
- It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or
- It can be written as `(A)`, where `A` 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.
Example 1:
Input: s = "())"
Output: 1
Example 2:
Input: s = "((("
Output: 3
Constraints:
- `1 <= s.length <= 1000`
- `s[i]` is either `'('` or `')'`.
Topics: String, Stack, Greedy
Approachβ
Stackβ
Use a stack (LIFO) to track elements that need future processing. Process elements when a "trigger" condition is met (e.g., finding a smaller/larger element). Monotonic stack maintains elements in sorted order for next greater/smaller element problems.
Matching brackets, next greater element, evaluating expressions, backtracking history.
Greedyβ
At each step, make the locally optimal choice. The challenge is proving the greedy choice leads to a global optimum. Look for: can I sort by some criterion? Does choosing the best option now ever hurt future choices?
Interval scheduling, activity selection, minimum coins (certain denominations), Huffman coding.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 116 ms)β
| Metric | Value |
|---|---|
| Runtime | 116 ms |
| Memory | 34.4 MB |
| Date | 2022-01-23 |
public class Solution {
public int MinAddToMakeValid(string s) {
int left = 0, right = 0;
for(int i=0;i<s.Length;i++)
{
if(s[i] == '(') right++;
else
{
if(right>0) right--;
else left++;
}
}
return left+right;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Stack | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Think about what triggers a pop: is it finding a match, or finding a smaller/larger element?