A stackis a basic linear data structure, in which the insertion and deletion of items happens at one end called top of the stack. It follows the order of LIFO (last in first out) or FILO (first in last out), the last element added to the stack will be the first element removed from the stack. The classic real-life example for stack is the stack of plates in a buffet, the plate at the top is always the first one to be removed. The stack data structure is commonly used in managing function invocations, undo/redo, and routing.

Image for post

Example of stacks (link)

There is no built-in stack data structure in JavaScript, but it is relatively simple to implement.

Array Implementation

Even though there is no built-in stack data structure in JavaScript, we use array data structure with the help of the push()pop()unshift(), and shift() methods to create stacks. Amongst these methods, unshift() and shift() need to reindex the elements in the array, thus it increases the time complexity. So push() and pop() are our first choices. To understand the array implementation of stacks better, let’s apply it to the leetcode problem below.

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

1. Open brackets must be closed by the same type of brackets.

2. Open brackets must be closed in the correct order.

#nodejs #programming #data-structures #stack #javascript

Stacks in JavaScript
2.85 GEEK