After I moved back to the United States and started school I had much less time to do personal stuff like coding and writing but today, my school district is closed so I have some time to do things that I want to do.

Thus, I decided to do some coding. I recalled that I did the Balanced Expressions coding interview problem but with so many for loops and difficult-to-understand logic and loops. Looking back, I surmise that the code will still work but the logic is very hard to understand, so I decided to look for a better approach.

I noticed that instead of looping through the character array and storing all the different types of brackets into one stack, we could make different stacks and push/pop each type of bracket according to their respective types. Specifically, if we encounter a ‘(‘ we would push this character into the type for parentheses instead of one for square brackets.

Using this logic I coded a function isBalancedOne that takes an array and a string and checks if it is balanced or not according to the array. The array needs to have an ‘opening’ and ‘closing’ bracket only, e.g. [‘(‘, ‘)’]. Then, we can duplicate this logic for different types of brackets, and if at least one of the functions returns false, then the original string is not balanced. It is balanced otherwise.

Here is the code I did for today:

This also demonstrates the theory that whenever you solve a hard problem and it looks messy, always look for a better and more efficient way to do that same problem. In fact, for any kind of problem that is not so straightforward, think about a slicker way to approach it. There will probably be a more organized way.

Leave a Reply or a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.