Given a string, that consist of only two types of characters: "(" and ")" . Balance the parentheses by inserting either a "(" or a ")" as many times as necessary.
Determine the minimum number of characters, that must be inserted. Example s = "(()))". To make it valid sequence should be inserted one "(" at the beginning . Now the string is balanced after one insertion. Answer is 1.
My problem here, in my try is that I make the string valid, but can't determine the minimum number of insertion, that should make the sequence valid.
let output = [];
function checkParanthesis(str) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === "(") {
output.push(str[i]);
count++;
} else if (str[i] === ")") {
if (output.pop() !== "(") {
count++
}
}
console.log(count);
}
return output.length;
}
checkParanthesis('()))')