Skip to main content

Minimum Add to Make Parentheses Valid

LeetCode 957 | Difficulty: Medium​

Medium

Problem 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.

When to use

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?

When to use

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.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 116 ms)​

MetricValue
Runtime116 ms
Memory34.4 MB
Date2022-01-23
Solution
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​

ApproachTimeSpace
Stack$O(n)$$O(n)$

Interview Tips​

Key Points
  • 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?