Stacks in JS and Parenthesis Matching

Photo by Annie Spratt on Unsplash

Stacks are a useful data structure that holds a list of elements. A stack works in a “last in”, “first out” principle meaning that the most recently added element is the first one to remove. The stack has two main methods that we use, .push() and .pop().

Explanation of the code above:

The reverse function takes in a string as an argument and returns it in reverse order through the following logic. First, we loop through the string and push each element into a stack we create. Lastly, we create an empty string and pop the elements of the stack into our string, and return it.

There are many applications of the use of stacks, such as reversing a string. The solution is to push each letter into the stack and then pop them back off. More examples of the stack applications are the “undo” mechanism in text editors, syntax parsing, function call, and expression conversion.

But I came across the need for a stack when trying to solve the problem of parenthesis matching. The problem is checking for a balanced number of MATCHING parenthesis or brackets i.e. “ (, ), [, ], {, }” and if not then how many and which should be added. For example, the function should return true for “{[(}])” and false for “{[)]” or “)(“.

The algorithm is as follows first we declare a variable stack as an empty array. Then, traverse the input string expression. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack. If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from the stack and if the popped character is the matching starting bracket then we can continue, else the parenthesis is not balanced. After complete traversal, if there is some starting bracket left in the stack then “not balanced”.

Resources: https://www.javascripttutorial.net/javascript-stack/