For the given string, determine if the open and closed brackets/parentheses are balanced are not, i.e. for every open bracket there must be a closed bracket in the same order. Return true if balanced and false if unbalanced.
🟢 Easy 🧩 Pattern – Stack
Example
Input: {(a+b)*(a-b)}
Output: Balanced
Input: {{(x+y)}
Output: Not BalancedCode language: JavaScript (javascript)Solution approach
This can be solved using a stack data structure and in JavaScript, we can create an array and treat it like a stack i.e. use only push and pop operations.
- First we push all open brackets into the stack as we read them
- Ignore all other characters, we only care about the brackets in this case
- Next, when we encounter a closed bracket it must match the last pushed item in the stack
lets take str = "[()]" and char will have the value at each iteration
1: char = “[” -> push -> stack = ["["]
2: char = “(” -> push -> stack =["[", "("]
3. char = “)” -> pop and compare -> “(” matches “)”
4. if any bracket pair doesn’t match then return false (extra closed bracket presence)
5. at the end of the loop if the stack contains any brackets then return false (extra open bracket presence)
Balanced Parentheses – JavaScript Code
function isBalanced(str) {
const stack = [];
const open = ["[", "{", "("];
const closed = ["]", "}", ")"];
const pairs = {
"]": "[",
"}": "{",
")": "(",
};
for (char of str) {
if (open.includes(char)) {
stack.push(char);
} else if (closed.includes(char)) {
const top = stack.pop();
if (pairs[char] !== top) {
// If the current closed bracket
// does not pair with the last pushed bracket
return false;
}
}
}
// If any unmatched brackets are left
const isEmpty = stack.length === 0;
return isEmpty;
}
const str = "[{(a+b)*(a-b)}]]";
console.log(isBalanced(str)); // Output: false
console.log(isBalanced("(){}[]")); // Output: true
console.log(isBalanced("([)]")); // Output: false
console.log(isBalanced("{[()]")); // Output: false
console.log(isBalanced("")); // Output: trueCode language: JavaScript (javascript)