Stack Data Structure: Operations, Code, Applications

A stack stores items last in, first out. Learn push, pop and peek, time complexity, overflow and underflow, JavaScript and Python code, and uses such as expression evaluation, bracket matching and the call stack.

Stack Data Structure: Operations, Code, Applications

Data structures are ways to store, organize and process data so that a program can use it efficiently. You must have seen how a bank’s cashier puts different currency notes in different sections of the drawer to make the transactions easier. Similarly, we need to store data in a structured way to perform operations easily.

There are multiple data structures for different use cases. In this article, we’ll learn about stack data structure: how it works, its operations and time complexity, JavaScript and Python code, and where stacks are used in real programs.

Introduction to Stack Data Structure

Stack is a linear data structure that stores elements in a specific order.

Let’s take our browser history as an example. When we jump to a new page, the previous page gets stored in the browser history. We can access that page by simply clicking the back button.  

This is possible because all the pages we’ve visited are stored in a new-to-old arrangement in the form of a stack. Hitting the back button opens up the page that is right below the newest page. 

A stack is an abstract data type (ADT): it defines what a stack can do, push, pop and peek, and leaves the storage to the implementation. A stack can have a fixed capacity (a bounded stack) or grow as needed. 

What is an Abstract data type?

ADTs specify the data and its applications but is independent of how it’s implemented. ADTs are implemented using different methods and logic in different programming languages.

These data structures are flexible and don’t depend on languages or machines. (Learn more about ADT here)

Stack follows a Last In First Out principle for adding or removing elements.

Consider a stack of books arranged in an order.

Now, if we want to take the bottom-most book out, we will have to take out the topmost book first, then the second, then the third until we finally reach the first one at the bottom.

The book that goes in last will be the first one to come out. This is called the LIFO principle. In the same case, the book added first will be removed at last which refers to the First In Last Out method aka FILO.

Last in first out principle: elements 1 to 5 sit in a stack, push adds a new element on top and pop removes the most recent one first

In typed languages such as Java or C++, a stack is usually declared to hold one type of element, for example a stack of integers. JavaScript and Python do not enforce that, so an array-based stack there can hold mixed values.

Every time we add an element, it goes to the top of the stack, and that’ll always be the first one to be removed from the stack. 

In other words, stacks can be defined as containers in which operations like insertion and deletion can only take place at one end.

How does Stack work?

To implement a stack, we need to keep a pointer to the ‘top’ of the stack i.e. the last element to be added. As the operations always happen at the top of the stack, this pointer always follows the topmost element.

Operations in Stack Data Structure

push() –  Push operation means adding/inserting an element into the stack.

pop() – Pop operation refers to removing an element from the stack. Pop always removes the element at the top of the stack and returns it.

peek() – This operation allows us to view the element which is at the top. There are no changes made in the stack here.

isEmpty() – It checks if the stack is empty or not to prevent the programmers from performing operations on an empty stack. This operation returns a boolean value – ‘True’ if size = 0, otherwise it returns ‘false’

isFull() – It’s not the opposite of isEmpty (a stack with room left is neither empty nor full): it returns ‘true’ if the stack is full, else returns ‘false’.

Now, let’s go through a step by step process to see how these operations come together-

1) While initializing the stack, we set the value of the pointer ‘top’ = -1. This value means that the stack is empty.

Empty stack with the top pointer at -1

2) When we add/push an element, the value increases to ‘top’ = 0, and the new element is placed in the position corresponding to the ‘top’ pointer.

Push operation in a stack: Data 1 is pushed into the empty stack and the top pointer points to it

3) Similarly, adding another element increases its value to ‘top = 1’ and the pointer comes up to the newest element.

Stack pointer moves up: after Data 2 is pushed, top points to Data 2, which sits above Data 1

4) Now, when we remove/pop an element, the pointer moves down by one, back to top = 0, to show that the topmost element is no longer a part of the stack. Its slot can be overwritten by the next push.

Pop operation in a stack: Data 2 is removed from the top and the top pointer moves back to Data 1
  • We check if the stack is already full before pushing.
  • We check if the stack is empty before implementing the pop operation.

A short trace

Here is a stack that starts empty and goes through a few operations. The top of the stack is on the right:

OperationStack after itReturns
push(10)10nothing
push(20)10, 20nothing
push(30)10, 20, 30nothing
peek()10, 20, 3030, and the stack does not change
pop()10, 2030
pop()1020
isEmpty()10false

Time complexity of stack operations

OperationTimeWhy
pushO(1)Writes one element at the top (amortized O(1) on a dynamic array that sometimes has to grow)
popO(1)Removes the element at the top
peekO(1)Reads the element at the top
isEmpty, isFull, sizeO(1)Compare the top pointer or a counter
Search for a valueO(n)You may have to pop through every element above it

Adding and removing at the end of a dynamic array, or at the head of a linked list, never moves the other elements, which is why a stack is fast (Wikipedia: stack).

Stack overflow and underflow

A bounded stack that is full cannot accept another push: that is stack overflow. Popping or peeking an empty stack is stack underflow. That is why the two checks above exist: test isFull before a push and isEmpty before a pop. A stack stored in a dynamic array or a linked list runs out of room only when memory runs out.

Implementation of JavaScript Stack using Arrays

A JavaScript array already has push() and pop() that work at the end of the array, so an array is the natural way to build a stack. The class below wraps them with the other stack operations. If arrays are new to you, start with the array data structure guide.

class Stack {
  constructor() {
    this.items = [];
  }

  // add an element on the top
  push(element) {
    this.items.push(element);
  }

  // remove and return the top element
  pop() {
    if (this.isEmpty()) return undefined;   // underflow: nothing to remove
    return this.items.pop();
  }

  // view the top element without removing it
  peek() {
    return this.items[this.items.length - 1];
  }

  // check if the stack is empty
  isEmpty() {
    return this.items.length === 0;
  }

  // the number of elements
  size() {
    return this.items.length;
  }

  // empty the stack
  clear() {
    this.items = [];
  }
}

const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
console.log(stack.peek());     // 30
console.log(stack.pop());      // 30
console.log(stack.pop());      // 20
console.log(stack.size());     // 1
console.log(stack.isEmpty());  // false

In the example above we create a new Stack class and implement push, pop, peek, isEmpty, size and clear. The pop() method returns undefined when the stack is empty instead of failing.

That version grows as needed. To see the top pointer from the steps earlier, here is a bounded stack in which top starts at -1, and push and pop check for overflow and underflow:

class BoundedStack {
  constructor(capacity) {
    this.data = new Array(capacity);
    this.top = -1;                       // -1 means the stack is empty
  }

  isEmpty() {
    return this.top === -1;
  }

  isFull() {
    return this.top === this.data.length - 1;
  }

  push(value) {
    if (this.isFull()) throw new Error('Stack overflow');
    this.top++;
    this.data[this.top] = value;
  }

  pop() {
    if (this.isEmpty()) throw new Error('Stack underflow');
    const value = this.data[this.top];
    this.top--;
    return value;
  }
}

const s = new BoundedStack(2);
s.push('A');
s.push('B');
console.log(s.top, s.isFull());          // 1 true
try {
  s.push('C');
} catch (e) {
  console.log(e.message);                // Stack overflow
}
console.log(s.pop(), s.pop());           // B A
try {
  s.pop();
} catch (e) {
  console.log(e.message);                // Stack underflow
}

In Python, a list works as a stack, with append() as push and pop() as pop:

stack = []                  # a Python list works as a stack
stack.append(10)            # push
stack.append(20)
stack.append(30)
print(stack[-1])            # peek: 30
print(stack.pop())          # pop: 30
print(stack.pop())          # pop: 20
print(len(stack), not stack)   # size and isEmpty: 1 False

Array or linked list?

A stack can also sit on a linked list, where push and pop work on the head node:

BasisArray or dynamic arrayLinked list
Push and popO(1), amortized for push on a dynamic arrayO(1) at the head
CapacityFixed for a bounded stack, grows for a dynamic arrayGrows one node at a time, so overflow only when memory runs out
MemoryElements sit side by sideEach node also stores a pointer to the next node
Best whenYou know the maximum size or want the simplest codeThe size is hard to predict

Most code uses the array version. For the linked-list version, see our linked list guide.

Applications of Stack Data Structure

Stacks show up wherever the most recent item must be handled first, or wherever a sequence of steps has to be reversed. This table lists the classic uses, and the sections below work through the main ones with code.

WhereHow the stack is used
Function callsThe call stack holds one frame for each active call, and the newest call finishes first
Expression evaluationPostfix (reverse Polish) expressions are evaluated with a stack of operands, and parsers use stacks too
Reversing dataPush everything, then pop it all: the order comes out reversed
Balanced bracketsPush opening brackets and pop on each closing bracket to check that they match
Backtracking and depth-first searchThe path so far sits on a stack, so you can step back to the last choice
UndoA simple model of undo: push every edit, and pop to reverse the latest one

Expression evaluation

Take the expression 6 * (2 + 4) + 16 / 4. A computer cannot just read it from left to right, because it has to respect the brackets and the precedence of the operators. The usual trick is to rewrite the expression in postfix form, also called reverse Polish notation, where each operator comes after its operands and no brackets are needed. The shunting-yard algorithm, invented by Edsger Dijkstra, converts an expression to postfix, and a stack then evaluates it (Wikipedia: reverse Polish notation).

The evaluation rule is short: read the tokens from left to right, push every number, and when you meet an operator, pop two numbers, apply the operator and push the result. When the tokens run out, the answer is the value left on the stack.

Our expression in postfix form is 6 2 4 + * 16 4 / +. This code prints the stack after every token:

def eval_postfix(tokens):
    stack = []
    for token in tokens:
        if token in ('+', '-', '*', '/'):
            b = stack.pop()                 # the right operand comes off first
            a = stack.pop()
            if token == '+':
                stack.append(a + b)
            elif token == '-':
                stack.append(a - b)
            elif token == '*':
                stack.append(a * b)
            else:
                stack.append(a / b)
        else:
            stack.append(int(token))        # a number: push it
        print(token, stack)                 # watch the stack change
    return stack.pop()

# 6 * (2 + 4) + 16 / 4 written in postfix
print(eval_postfix('6 2 4 + * 16 4 / +'.split()))

Output:

6 [6]
2 [6, 2]
4 [6, 2, 4]
+ [6, 6]
* [36]
16 [36, 16]
4 [36, 16, 4]
/ [36, 4.0]
+ [40.0]
40.0

The result is 40, the same as working it out by hand: the bracket gives 6, then 6 * 6 = 36, 16 / 4 = 4, and 36 + 4 = 40. (Python's / always returns a decimal, so the answer prints as 40.0.)

Converting Decimal to binary

We use stacks to find the equivalent binary number for a decimal number.

How? We divide the number by 2 again and again and store each remainder (0 or 1) in a stack. The remainders come out last digit first, which is the wrong way round. When the number reaches 0, we pop the digits one at a time, and the stack hands them back in reverse, which is the right order.

For 13: 13 divided by 2 is 6 with remainder 1, 6 divided by 2 is 3 with remainder 0, 3 divided by 2 is 1 with remainder 1, and 1 divided by 2 is 0 with remainder 1. The stack holds 1, 0, 1, 1 with the last 1 on top. Popping gives 1, 1, 0, 1, so 13 in binary is 1101.

def to_binary(n):
    stack = []
    while n != 0:
        stack.append(n % 2)         # remainders come out last digit first
        n //= 2
    bits = ''
    while stack:
        bits += str(stack.pop())    # popping reverses them
    return bits or '0'

print(to_binary(13))                # 1101

Reversing a String

The characters of a string can be reversed using a stack. We use the basic ‘push’ and ‘pop’ functions to do this. First, we push the characters one by one into the stack.

Let’s take the word ‘MASAI’ as an example.

Reversing the string MASAI with a stack: the letters are pushed in order and popped back out as IASAM

As stack follows the last in first out principle, the last element to go in would be the first one to come out. We’ll use the pop function one by one to print the reversed string.

Popping all five letters gives IASAM, as the picture shows. In code:

def reverse(text):
    stack = []
    for ch in text:
        stack.append(ch)            # push every character
    out = ''
    while stack:
        out += stack.pop()          # pop them back: last in, first out
    return out

print(reverse('MASAI'))             # IASAM

Checking balanced brackets

Parsers have to check that every opening bracket has a matching closing bracket in the right order. A stack does it in one pass: push each opening bracket, and when a closing bracket arrives, pop the top and check that the two match. The text is balanced only if every closing bracket found a match and the stack is empty at the end.

def is_balanced(text):
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in text:
        if ch in '([{':
            stack.append(ch)                  # opening bracket: push
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False                  # closing bracket with nothing to match
    return not stack                          # leftover openers mean unbalanced

print(is_balanced('{[()]}'))    # True
print(is_balanced('{[(])}'))    # False
print(is_balanced('(()'))       # False

The second string fails because the ) arrives while [ is on top of the stack. The third fails because an opening bracket is left over at the end.

Backtracking

We use stacks in backtracking. Backtracking solves complex problems using recursive algorithms.

Let’s say we have to solve a maze puzzle. We choose one path and if we get stuck somewhere in the middle or reach the wrong target, we come back to the starting point. Then we take another path and the process goes on until we find the optimal solution.

In this process, we have to store the previous path to be able to track back to the initial position. That’s where we use a stack.

It stores the previous solution to the problem which is then used to try a new solution.

Depth-first search on a graph works the same way. It keeps the path it has taken on a stack (or on the call stack, when it is written recursively) and goes back to the last choice when it reaches a dead end. Breadth-first search swaps the stack for a queue.

Function Calls

We use stacks in programs that call functions in succession. Let’s say there is a function X which calls the function Y, and Y calls the function Z.

Now, we can only process function X if function Y is completed and returned. Similarly, for Y, the function Z needs to return.

We can see that the function X is the first one to get started but the last one to return. This should remind you of the FILO principle in stacks.

And, that’s why stack is the ideal structure for handling function calls.

You can watch the call stack work with a function that prints a line when it starts and another when it returns:

def factorial(n):
    indent = '  ' * (3 - n)
    print(indent + 'call factorial(' + str(n) + ')')
    result = 1 if n == 1 else n * factorial(n - 1)
    print(indent + 'return ' + str(result))
    return result

factorial(3)

Output:

call factorial(3)
  call factorial(2)
    call factorial(1)
    return 1
  return 2
return 6

factorial(3) calls factorial(2), which calls factorial(1). The most recent call returns first, then the one before it, then the first: last in, first out. Each call adds a frame to the call stack that holds its arguments, its local variables and the return address, and each return removes it (Wikipedia: call stack).

If recursion has no base case, or goes too deep, the frames use up all the memory set aside for the call stack and the program fails with a stack overflow (Python raises a RecursionError). Our guide to recursion shows how to write the base case and when a loop is the better choice.

Stack vs queue

A stack and a queue are both linear structures, but they hand elements back in opposite orders.

BasisStackQueue
PrincipleLast In First Out (LIFO)First In First Out (FIFO)
Where elements are added and removedBoth at the topAdded at the rear, removed from the front
Main operationspush, pop, peekenqueue, dequeue, peek
PointersOne: topTwo: front and rear
Everyday exampleA pile of books, or the browser back buttonPeople in a line at a ticket counter
Typical usesFunction calls, expression evaluation, backtrackingScheduling, breadth-first search, buffers

Read the queue data structure guide for the other side, and the applications of queue guide for where queues are used.

Common stack interview problems

Many stack questions use one of a few patterns:

ProblemIdea
Valid ParenthesesPush opening brackets, pop on every closing one and check the pair. The stack must be empty at the end.
Evaluate Reverse Polish NotationThe postfix rule above: push numbers, and pop two on every operator.
Min StackStore the smallest value so far next to each element, so the minimum is always available in O(1).
Next Greater ElementKeep a stack of values in decreasing order. Each element is pushed and popped once, so the total time is O(n).
Implement Queue using StacksUse two stacks, and pour one into the other when the front stack is empty. This reverses the order twice, which gives FIFO.

If you want to understand data structures and algorithms from scratch, here is our beginner's guide to DSA.

Frequently asked questions

What is a stack in data structure?

A stack is a linear data structure in which elements are added and removed at one end only, called the top. The last element pushed is the first one popped, which is why a stack is called last in, first out (LIFO).

What are the basic operations of a stack?

Push adds an element on top, pop removes and returns the top element, peek reads the top without removing it, isEmpty checks whether the stack has no elements, and isFull checks whether a fixed-capacity stack has no room left.

What are the applications of a stack?

Common applications are the function call stack, evaluating expressions in postfix form, matching brackets, backtracking and depth-first search, and reversing data such as a string. A simple undo feature can be modelled the same way, with each edit pushed and undo popping the latest one.

What is stack overflow and underflow?

Overflow happens when you push onto a bounded stack that is already full. Underflow happens when you pop or peek an empty stack. The call stack can also overflow when recursion goes too deep, for example when a recursive function has no base case.

What is the time complexity of stack operations?

Push, pop, peek and isEmpty take O(1) time in an array or linked-list stack (push is amortized O(1) on a dynamic array that sometimes has to grow). Searching for a value takes O(n), because you may have to pop through every element above it.

What is the difference between a stack and a queue?

A stack is last in, first out and works at one end only. A queue is first in, first out: elements are added at the rear and removed from the front. Use a stack for nested or reversing problems such as function calls, and a queue for work that must be handled in arrival order.

×

Our Courses

Practice-Based Learning Tracks, Supercharged By A.I.