Skip to content

Instantly share code, notes, and snippets.

@Toscan0
Last active April 6, 2023 17:28
Show Gist options
  • Save Toscan0/1bc623a6a9b9c696aebdf1095202f5b2 to your computer and use it in GitHub Desktop.
Save Toscan0/1bc623a6a9b9c696aebdf1095202f5b2 to your computer and use it in GitHub Desktop.
Check if an expression is balanced or not. Return the index. if not balanced
const checkBalancedExpr = (expr) => {
let stack = [];
for(let i = 0; i < expr.length; i++) {
let char = expr[i];
const brackets = ['(', ')', '[', ']', '{', '}']
if(!brackets.includes(char)) {
continue;
}
if (char === '(' || char === '[' || char === '{') {
stack.push(char);
continue;
}
if (stack.length === 0) {
return [false, i];
}
let check = stack.pop();
switch (char) {
case ')':
if (check !== '(') {
return [false, i];
}
break;
case '}':
if (check !== '{') {
return [false, i];
}
break;
case ']':
if (check !== '[') {
return [false, i];
}
break;
}
}
if (stack.length === 0) {
return true;
}
return [false, stack.length - 1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment