The Indian Engineer

Problem 921 Minimum Add to Make Parentheses Valid

Posted on 5 mins

String Stack Greedy

Problem Statement

Link - Problem 921

Question

A parentheses string is valid if and only if:

You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.

Return the minimum number of moves required to make s valid.

Example 1:

Input: s = "())"
Output: 1

Example 2:

Input: s = "((("
Output: 3

Constraints:

Solution

class Solution {
public:
    int minAddToMakeValid(string s) {
        cin.tie(0);
        int open=0,close=0;
        for(auto &ch:s){
            if(ch == '(')
                open++;
            else
                open>0?open--:close++;
        }
        return open+close;
    }
};

Complexity Analysis

| Algorithm             | Time Complexity | Space Complexity |
| --------------------- | --------------- | ---------------- |
| Single-pass traversal | O(n)            | O(1)             |

Explanation

Intial Thoughts

To solve this problem, we should first consider how we balance parentheses in everyday writing, like keeping track of opening and closing brackets in a sentence. We need to find the minimum number of additions required to achieve this balance in a string. The approach should involve counting the number of unmatched opening and closing parentheses and determining the minimum operations needed to match them. This could involve iterating through the string to keep track of the balance between opening and closing parentheses. Key points to consider include how to handle consecutive opening or closing parentheses and how to efficiently calculate the minimum additions required.

Intuitive Analysis

An intuitive way to think about this problem is to imagine a stack of blocks, where opening parentheses represent adding a block to the stack and closing parentheses represent removing a block. If the stack is empty when we encounter a closing parenthesis, it means we need an opening parenthesis to balance it, so we increment our count of additions needed. Similarly, if there are blocks left in the stack at the end, it means we have unmatched opening parentheses, so we also need to increment our count of additions for these. This ‘stack’ analogy helps simplify the problem into keeping track of the balance between opening and closing parentheses and calculating the minimum additions required to achieve a balanced string.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.


Similar Questions:

Title URL Difficulty
Minimum Number of Swaps to Make the String Balanced https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced Medium