JS Coding Question #10: Is Balanced Parenthesis [Very Common Question]

frontendengineer

Let's Code

Posted on September 30, 2021

JS Coding Question #10: Is Balanced Parenthesis [Very Common Question]

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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 πŸ‘πŸ˜Š

πŸ’– πŸ’ͺ πŸ™… 🚩
frontendengineer
Let's Code

Posted on September 30, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related