Minimum Add to Make Parentheses Valid — LeetCode 921 Python Solution

MediumStackGreedyString
Problem
#921
Pattern
Stack
Reading time
2 min

The problem

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.

Example

Input
s = "())"
Output
1

Python solution

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

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the string s auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 921. Minimum Add to Make Parentheses Valid is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 921. Minimum Add to Make Parentheses Valid?
LeetCode 921. Minimum Add to Make Parentheses Valid is rated Medium on LeetCode.
What is the time complexity of LeetCode 921. Minimum Add to Make Parentheses Valid?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 921. Minimum Add to Make Parentheses Valid?
The Python solution on this page uses O(n), where n is the length of the string s auxiliary space.
What topics does LeetCode 921. Minimum Add to Make Parentheses Valid cover?
LeetCode 921. Minimum Add to Make Parentheses Valid is tagged Stack, Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview