Checking whether a series of parenthesis is balanced and valid is a classic puzzle in computer science and can be easily met during a job interview.

In my opinion, there is no better solution than using a regular expression and solve the problem with a single (but almost unreadable) line of code, however I'd like to describe an algorithm which can be easily implemented in any functional or imperative programming language.

The idea is simple: start from the first character and check if it is an opening parenthesis. In this case we have to push it on a LIFO data structure such as a stack and continue with the next character.

If the character is a closing parenthesis, we take (pop) the top element from the stack and check if it makes a valid couple of brackets with the examined element.

If this is not the case, the series is not balanced, otherwise we can discard both parenthesis and go on with the next character, until the series is over.

When there are no parenthesis left to examine, if the stack is empty our series is valid; if there are still elements on the stack we can conclude that the series is unbalanced.

remember that = is the comparison operator, as the == operator in other languages.

This line says: when char_array is empty, if the stack is empty return true, otherwise return false.

Actually, I didn’t use the is_closing function and I assumed that every character that is not an opening bracket will be a closing one.

To be safe, I’d add another line to the first pattern matching and check if the examined character is a closing parenthesis.
Any other character should warn the user that the input string is not valid.

Just to be theoretical , remember that “pure” regular expressions (I mean: something that can be translated into finite automatons) aren’t expressive enough to solve the balanced-parenthesis problem.
It is also true that most regular expressions implementations are expanded so to fit also this as a special case.