AlgoMaster Logo

Introduction to Stacks

High Priority8 min readUpdated November 9, 2026
Listen to this chapter
Unlock Audio

Introduction to Stacks

A stack is one of the simplest data structures in computer science, but it's also incredibly useful.

It follows a simple rule called LIFO: Last In, First Out.

This means the last element you add to a stack is the first one to be removed.

Loading simulation...

Despite its simplicity, stacks are used everywhere:

  • Compilers use them to evaluate expressions.
  • Text editors use them to implement undo and redo.
  • Your programs use a call stack to keep track of function calls.
  • Algorithms like DFS and backtracking rely on stacks as well.

In this chapter, we'll understand what a stack is and how it works.

We'll explore its basic operations, their time complexities, and different ways to implement a stack.

And finally, we'll look at some common patterns where stacks are useful, especially in coding interviews.

What is a Stack?

Think about a stack of plates in your kitchen.

You wash a plate and place it on top of the stack. Then you wash another plate and place it on top of the previous one.

Now, when you need a plate, you take the one at the top, which is the plate you added most recently.

You can't take a plate from the middle without removing the ones above it first.

And that's exactly how a stack works. It is a linear data structure where elements are added and removed from only one end, called the top.

Stack Operations

A stack supports four common operations.

1. Push

Push simply adds a new element to the top of the stack.

For example, suppose our stack contains 1, 2, and 3, with 3 at the top.

1
2
3
top

If we push 4, it gets added above 3 and becomes the new top.

1
2
3
4
top

2. Pop

Pop removes the top element and returns it.

So if we pop from our current stack, we get back 4, leaving 1, 2, and 3.

1
2
3
top

3 is now the top again.

3. Peek

Peek, sometimes called top, lets us see the top element without removing it.

So unlike pop, it doesn't change the stack. Calling peek on the stack above returns 3, and the stack stays 1, 2, 3.

4. isEmpty

isEmpty checks whether the stack contains any elements.

For example, if we pop 3, then 2, and finally 1, our stack becomes empty.

At this point, isEmpty returns true.

This is particularly useful when we want to avoid popping from an empty stack. Popping from an empty stack is an error, often called a stack underflow.

Time and Space Complexity

Here's what makes stacks so efficient.

All four operations take O(1) time, because we only need to access the top of the stack. There's no need to search through elements or shift anything around.

Operation

Time Complexity

push

O(1)

pop

O(1)

peek

O(1)

isEmpty

O(1)

As for space complexity, storing n elements requires O(n) space.

So stacks give us constant-time access to the most recently added element, while using memory proportional to the number of elements stored.

Stack Implementation

How do we implement a stack ourselves? There are two common approaches: we can use an array or a linked list.

Let's look at both.

1. Using an Array

The idea is straightforward.

We maintain an array and a variable called top, which keeps track of the index of the top element.

Since all operations happen at the end of the array, they take O(1) time.

  • In the constructor, we create an array of the given capacity and initialize top to -1, indicating an empty stack.
  • For push, we first check whether there's enough space. If there is, we increment top and store the new element at that index.
  • For pop, we check whether the stack is empty. If it isn't, we return the top element and decrement top.
  • For peek, we simply return the element at top without removing it.
  • For isEmpty, we check whether top is equal to -1.

In this code, pushing onto a full stack prints "Stack Overflow", and popping or peeking an empty stack prints a message and returns -1. In production code, you would usually throw an exception instead.

The main limitation here is that our array has a fixed capacity.

Once it's full, we can't push more elements without resizing it.

Fortunately, modern languages provide dynamic arrays, like ArrayList in Java and list in Python, that handle resizing automatically.

2. Using a Linked List

In the linked list implementation, the head of the linked list represents the top of our stack.

Whenever we push an element, we create a new node at the beginning of the list.

Here's how it works step by step:

  1. Push 1. Head points to 1.
  2. Push 2. We create a new node, point it to 1, and make 2 the new head.
  3. Push 3. 3 becomes the head.
  4. Pop. We remove the head and move it to the next node, so head now points to 2.
  5. Pop again. Head moves to 1.
1Push 1: head points to 1
1
head
null
1/5

Since we only work with the head, all these operations take O(1) time.

Here's what the linked list implementation looks like in code.

  • For push, we create a new node, connect it to the current head, and update head to point to the new node. That node becomes our new top.
  • For pop, we first check whether the stack is empty. Otherwise, we save the head's value, move head to the next node, and return the saved value.
  • For peek, we return the head's value without removing it.
  • For isEmpty, we simply check whether head is null.

Array vs Linked List

So which implementation should you choose?

An array stores elements together in memory, making it more memory-efficient. But with a fixed array, we need to handle capacity limits and resizing ourselves.

A linked list grows dynamically without resizing, but every node requires an extra pointer, increasing memory overhead.

Both approaches support constant-time stack operations, although resizing a dynamic array can occasionally make a push more expensive.

Scroll

 

Array

Linked List

push / pop / peek

O(1) (amortized O(1) push with a dynamic array)

O(1)

Size

Fixed, unless you resize

Grows and shrinks as needed

Memory per element

Just the value

Value plus a next pointer

Memory layout

Contiguous, cache-friendly

Nodes spread across memory

Built-in Stacks

In practice, you rarely need to implement a stack from scratch.

Most programming languages already provide efficient, well-tested ways to use stacks.

In Java, the recommended approach is to use the Deque interface with ArrayDeque.

We create an ArrayDeque and push three elements onto it. Calling peek returns 3 without removing it. Calling pop removes and returns 3. And isEmpty tells us whether the stack is empty.

Under the hood, ArrayDeque uses a resizable array. Push and pop operate at the same end, giving us O(1) amortized time.

Java also has an older Stack class, but ArrayDeque is generally preferred for stack operations.

All these built-in options are efficient and work well for most use cases.

So unless an interviewer specifically asks you to implement a stack, it's usually better to use the standard library.

When to Use a Stack

Now comes an important question for coding interviews: when should you use a stack?

There are a few common patterns worth recognizing.

  1. Matching pairs, like parentheses, brackets, or HTML tags. Whenever you need to match a closing symbol with the most recent unmatched opening symbol, a stack is a natural choice.
  2. Undo operations. We can push each action onto a stack and pop the most recent action whenever the user presses undo.
  3. Reversing elements. Push elements onto a stack, then pop them one by one, and their order is automatically reversed.
  4. Depth-first search. We use a stack to traverse trees and graphs iteratively. And when we use recursive DFS, the programming language's call stack handles this for us.
  5. Monotonic stack. This is a useful technique for problems involving the next greater or smaller element. It can help solve many such problems in O(n) time.

Summary

And that's the stack data structure.

  • A stack follows LIFO: the last element added is the first one removed.
  • push, pop, peek, and isEmpty all run in O(1) time, and the stack takes O(n) space.
  • You can implement it with an array (memory-efficient, fixed capacity unless resized) or a linked list (grows freely, extra pointer per node).
  • In practice, use your language's built-in option, like ArrayDeque in Java, list in Python, or std::stack in C++.

To really understand these concepts, I'd recommend implementing a stack yourself using both an array and a linked list.

Working through push, pop, peek, and handling an empty stack will help you build a much stronger understanding of how stacks work behind the scenes.

Quiz

Introduction to Stack Quiz

10 quizzes