JS Coding Question #10: Is Balanced Pare ...

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

Oct 01, 2021

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!

Video below if you prefer instead of bunch of text/code.

https://youtu.be/1TjtX4HR44w

Enjoy this post?

Buy letscode77 a coffee

More from letscode77