Leetcode #921 Minimum Add to Make Parentheses Valid

Leetcode #921 Minimum Add to Make Parentheses Valid

Difficulty: Medium

This question is not that difficult. It can be solved using 2 structures to keep track of the open and closing parentheses.

Thought process:

  • First, check if the string is empty. Return 0 if true.
  • Loop through the string, keep track of the opening parentheses.
  • If we encounter a closing parenthesis, check if we have an open parenthesis to match.
  • If yes, we pop it. Otherwise, we push the closing parenthesis.
  • The return value should be the length of both open and close parentheses.

Time complexity: O(n)

/**
 * @param {string} s
 * @return {number}
 */
var minAddToMakeValid = function(s) {
    let ret = 0;
    let open = [];
    let close = [];

    if(s.length == 0){
        return 0;
    }

    for(let i =0;i<s.length;i++){
        if(s[i] == "("){
            open.push("(");
        }

        if(s[i] == ")"){
            if(open.length >0){
                open.pop();
            }else{
                close.push(")");
            }
        }
    }

    ret = open.length + close.length;

    return ret;
};