The task:
Given a string of parentheses, write a function to compute the minimum number of parentheses to be removed to make the string valid (i.e. each open parenthesis is eventually closed).
For example, given the string "()())()", you should return 1. Given the string ")(", you should return 2, since we must remove all of them.
const brackets = "()())()";
My functional solution:
const numberOfUnbalanced = brackets => Object.values(brackets
.split("")
.reduce((brackCounter, b) => {
b === "(" ? brackCounter.openBrackets++ :
brackCounter.openBrackets ? brackCounter.openBrackets-- :
brackCounter.closedBrackets++;
return brackCounter;
}, {openBrackets: 0, closedBrackets: 0}))
.reduce((sum, b) => sum + b, 0);
console.log(numberOfUnbalanced(brackets));
My imperative solution:
function numberOfUnbalanced2(brackets) {
let openBrackets = 0, closedBrackets = 0;
for (let i in brackets) {
brackets[i] === "(" ? openBrackets++ :
openBrackets ? openBrackets-- :
closedBrackets++;
}
return openBrackets + closedBrackets;
}
console.log(numberOfUnbalanced2(brackets));
Usually the functional approach is shorter and tend to be easier to understand in comparison to imperative approaches. However, in this case it doesn't have any advantage to the imperative approach. I guess it is due to the nested structure in the functional solution.