Skip to content

Instantly share code, notes, and snippets.

@sagrath23
Created October 3, 2023 16:34
Show Gist options
  • Save sagrath23/bb272cd241321e31be2fb0719e395866 to your computer and use it in GitHub Desktop.
Save sagrath23/bb272cd241321e31be2fb0719e395866 to your computer and use it in GitHub Desktop.
balanced brackets
const OPEN_SYMBOLS = ['{', '[', '('];
const CLOSE_SYMBOLS = {
')': '(',
']': '[',
'}': '{'
};
function isBalanced(s) {
const heap = [];
for(let i = 0; i < s.length; i++) {
const symbol = s[i];
if(OPEN_SYMBOLS.includes(symbol)) {
// push to heap
heap.push(symbol);
} else {
if(heap[heap.length - 1] === CLOSE_SYMBOLS[symbol]) {
// if match, pop the open symbol from heap
heap.pop();
} else {
return 'NO';
}
}
}
return heap.length === 0 ? 'YES' : 'NO';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment