Created
October 3, 2023 16:34
-
-
Save sagrath23/bb272cd241321e31be2fb0719e395866 to your computer and use it in GitHub Desktop.
balanced brackets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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