Brace Validation

Yesterday I did the valid parentheses problem and came up with two solutions, that worked. One was overthought while the other was simplicity defined. The next logical question one can ask though is what if we now want to do brace validation? I.e. there are more than just brackets? What if we include curly braces{}, and square brackets?

Example

  • {}()[] should be valid
  • [} should be invalid

First thoughts on Brace validation

The first thing that went into my mind is that we’d need to now check which braces we got and compare them to their matching closing bracket. Then how would you do that, maybe store the pairs in an object…

Seriously, that’s how my thought process started. But then I remembered yesterday, took a deep breath, and thought what would be the least amount of code I could add to get it to work. What are we actually trying to achieve?

We want to match all closed brackets.

Solution

When you think about it, the logic doesn’t change. We don’t need an object or conditional checks or anything complicated. We just need to change the stopping criteria and the replace regex. That’s all. So I updated yesterday’s code to be;

function validBraces(parens) {
    let workString = parens
    const re = /(\(\))|(\{\})|(\[\])/g
    while(workString.search(re) !== -1) {
        workString = workString.replace(re,'')
    }
    return workString === ''
}
Code language: JavaScript (javascript)

That’s it. That’s all there was to it. Just updating the regex and everything else stayed the same. I also switched from indexOf to search but that’s a trivial quibble.

Could the previous approach also be updated with so little code? No, because we’d need to update the isMatch to account for the other types of brackets.

I think this makes yesterday’s final solution the better of the two because it is super easy to extend. Software should be soft, i.e. easy to change when new requirements occur. This solution was easy to extend, well easier than the previous one at least.

If you made your own solution to yesterday’s problem, how easy would it be to update it to fit the new requirements? Let me know over on Twitter @phoexer and as always happy coding.