How to check for Balanced Strings in Javascript

📅 January 25, 2021

👷 Chris Power

As part of my ongoing interview question in javascript series. I am going present a very common javascript interview question that I have come across time and time again. The question goes like this:

Write a function that can check the balance of brace characters in a string. Return true if the string is balanced (I.E. ”(){}” is balanced, and ”{{}” is not).

There are a lot of ways one could solve this problem, and there are some performance gains someone could employ if needed. However, I’d like to show what I feel is the most straightforward, and explicit solution to this interview question. Video Below:

Here is the code:

const braceMap = {
  '{': {
    name: 'squiggly',
    type: 'open',
  },
  '}': {
    name: 'squiggly',
    type: 'closed',
  },
  '[': {
    name: 'square',
    type: 'open',
  },
  ']': {
    name: 'square',
    type: 'closed',
  },
  '(': {
    name: 'parentheses',
    type: 'open',
  },
  ')': {
    name: 'parentheses',
    type: 'closed',
  },
}

function testForBalance(testString) {
  let braceStack = []

  testString.split('').map(element => {
    const braceElement = braceMap[element]
    if (braceElement) {
      if (braceElement.type === 'open') {
        braceStack.push({ ...braceElement })
      }
      if (braceElement.type === 'closed' && braceStack.length > 0) {
        if (braceStack[braceStack.length - 1].name === braceElement.name) {
          if (braceStack[braceStack.length - 1].type === 'open') {
            braceStack.pop()
          } else {
            braceStack.push({ ...braceElement })
          }
        } else {
          braceStack.push({ ...braceElement })
        }
      } else if (braceElement.type === 'closed' && braceStack.length === 0) {
        braceStack.push({ ...braceElement })
      }
    }
  })

  return braceStack.length === 0 // if 0; balanced. otherwise; unbalanced
}

// Write a function that tests the balance of a string's brace characters.
// Should account for {}, [], and ()
console.log(testForBalance('{[]}')) // true
console.log(testForBalance('{(func) => ([])}')) // true
console.log(testForBalance('Whats { up {')) // false
console.log(testForBalance('} {')) // false
Lets Work Together

We're trusted by large, medium, and small companies all over the world

Have something you're working on?

Tell Us About It