921. Minimum Add to Make Parentheses Valid

1 min read

LeetCode Daily Problem: Minimum Add to Make Parentheses Valid

On this page

Original problem on LeetCode

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.

Constraints:

  • 1 <= s.length <= 1000
  • s[i] is either '(' or ')'.

Approach: Stack

I started with some wild ideas, but they failed. In the end, brackets still call for a stack.

With a stack it is simple: cancel every matched pair and leave the unmatched ones. Each leftover bracket needs one extra partner.

python
class Solution:
    def minAddToMakeValid(self, s: str) -> int:
        stack = []
        for c in s:
            if c == '(':
                stack.append(c)
            else:
                if stack and stack[-1] == '(':
                    stack.pop()
                else:
                    stack.append(c)
        return len(stack)

Complexity

  • Time: O(n) — one pass.
  • Space: O(n) — the stack.
TagsStack

Back to all posts