This content originally appeared on DEV Community and was authored by Let's Code
Interview Question #10:
Write a function or program that checks if a string is a balanced parenthesis.?
If you need practice, try to solve this on your own without looking at the solution below.
Feel free to bookmark ? even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.
Codepen:
If you want to play around and experiment with the code: https://codepen.io/angelo_jin/pen/OJgwaed
Solution below uses a stack which is a great algorithm to use in this kind of problem. With a small tweak on the code below, you can solve problem that checks for balanced curly braces, brackets and parenthesis as well.
function isBalanced(str) {
const stack = []
for (let char of str) {
if ( char === '(' ) {
stack.push(char)
} else {
if ( stack.pop() !== '(' ) {
return false
}
}
}
if (stack.length !== 0) return false
return true
}
Small Cleanup/Refactor
function isBalanced(str) {
const stack = []
for (let char of str) {
if ( char === '(' ) {
stack.push(char)
} else if ( stack.pop() !== '(' ) {
return false
}
}
return stack.length !== 0 ? false : true
}
Happy coding and good luck if you are interviewing!
If you want to support me - Buy Me A Coffee
Video below if you prefer instead of bunch of text/code ??
This content originally appeared on DEV Community and was authored by Let's Code

Let's Code | Sciencx (2021-09-30T04:40:45+00:00) JS Coding Question #10: Is Balanced Parenthesis [Very Common Question]. Retrieved from https://www.scien.cx/2021/09/30/js-coding-question-10-is-balanced-parenthesis-very-common-question/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.