Balanced Brackets with Stack & Map
Spot the subtle bug in a bracket-matching function using a stack and a hash map of pairs.
Codejavascript
function isBalanced(str) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const ch of str) {
if (ch === '(' || ch === '[' || ch === '{') {
stack.push(ch);
} else if (pairs[ch]) {
if (stack.pop() !== pairs[ch]) return false;
}
}
return true;
}
console.log(isBalanced("([)]")); // false
console.log(isBalanced("(([")); // should be falseWhat is the bug in this bracket-matching code?