Stack Data Structure

LIFO principle, operations, implementations and applications

Introduction

A Stack is a linear data structure that follows the LIFO (Last In First Out) principle.

This means that the last element inserted into the stack is the first element removed.

Think of a stack of plates:

  • You place a new plate on the top.
  • You remove a plate from the top.
  • The last plate placed is the first one removed.

This behavior is exactly how a stack works.


Real Life Examples of Stack

Stack of Plates

Top
 ↓
[Plate 4]
[Plate 3]
[Plate 2]
[Plate 1]

Removing a plate removes the topmost plate first.


Browser History

When visiting web pages:

Google
↓
YouTube
↓
GitHub
↓
StackOverflow

Pressing Back:

StackOverflow removed
GitHub removed
YouTube removed

The most recently visited page is accessed first.


Undo Operation

Applications such as:

  • Microsoft Word
  • VS Code
  • Photoshop

Store actions in a stack.

Type Hello
Type World
Delete Word

Undo removes the most recent action first.


Stack Representation

Top
 ↓
+-----+
| 30 |
+-----+
| 20 |
+-----+
| 10 |
+-----+

The top element is always the first element accessed.


Basic Stack Operations

Push

Adds an element to the top of the stack.

Example

Stack:

10
20

Push 30:

30 ← Top
20
10

Pop

Removes the top element from the stack.

Example

Before:

30 ← Top
20
10

After Pop:

20 ← Top
10

Removed Element:

30

Peek (Top)

Returns the top element without removing it.

Example

30 ← Top
20
10

Peek:

30

Stack remains unchanged.


isEmpty()

Checks whether the stack contains elements.

Example

stack.isEmpty();

Returns:

true

if stack contains no elements.


Size()

Returns total number of elements.

Example:

10
20
30
40

Size:

4

Stack Operations Visualization

Initially:

Empty Stack

Push(10)

10

Push(20)

20
10

Push(30)

30
20
10

Pop()

20
10

Peek()

20

Time Complexity of Stack Operations

OperationTime Complexity
PushO(1)
PopO(1)
PeekO(1)
isEmptyO(1)
SizeO(1)

Stack operations are very efficient because they only operate at the top.


Stack Implementation Using Array

Java Implementation

class Stack {

    private int[] arr;
    private int top;
    private int capacity;

    public Stack(int size) {
        arr = new int[size];
        capacity = size;
        top = -1;
    }

    public void push(int value) {

        if(top == capacity - 1) {
            System.out.println("Stack Overflow");
            return;
        }

        arr[++top] = value;
    }

    public int pop() {

        if(top == -1) {
            System.out.println("Stack Underflow");
            return -1;
        }

        return arr[top--];
    }

    public int peek() {

        if(top == -1)
            return -1;

        return arr[top];
    }

    public boolean isEmpty() {
        return top == -1;
    }
}

Stack Overflow

Occurs when attempting to insert into a full stack.

Example:

Capacity = 3

30
20
10

Push(40)

Stack Overflow

Stack Underflow

Occurs when attempting to remove from an empty stack.

Example:

Empty Stack

Pop()

Stack Underflow

Stack Implementation Using Linked List

A linked list can dynamically grow and shrink.


Node Structure

class Node {

    int data;
    Node next;

    Node(int data) {
        this.data = data;
    }
}

Stack Implementation

class Stack {

    private Node top;

    public void push(int value) {

        Node node = new Node(value);

        node.next = top;
        top = node;
    }

    public int pop() {

        if(top == null)
            return -1;

        int value = top.data;

        top = top.next;

        return value;
    }

    public int peek() {

        if(top == null)
            return -1;

        return top.data;
    }
}

Java Built-in Stack Class

Java provides a Stack class.

import java.util.Stack;

public class Main {

    public static void main(String[] args) {

        Stack<Integer> stack = new Stack<>();

        stack.push(10);
        stack.push(20);
        stack.push(30);

        System.out.println(stack.pop());

        System.out.println(stack.peek());
    }
}

Output:

30
20

Modern Java applications generally prefer Deque over Stack.

import java.util.ArrayDeque;
import java.util.Deque;

Deque<Integer> stack = new ArrayDeque<>();

stack.push(10);
stack.push(20);

System.out.println(stack.pop());

Applications of Stack

Stacks are widely used in software systems.


Function Call Management

When a function is called, it is pushed onto the call stack.

Example:

main()
    methodA()
        methodB()

Call Stack:

methodB
methodA
main

When methodB finishes:

methodA
main

Recursion

Recursive calls are managed using the call stack.

Example:

factorial(3)

Call Stack:

factorial(3)
factorial(2)
factorial(1)

Expression Evaluation

Used to evaluate:

(2 + 3) * 4

Parentheses Matching

Checking whether:

((()))

is balanced.


Browser Navigation

Used for:

  • Back button
  • Forward button

Undo / Redo Operations

Applications maintain stacks of actions.

Examples:

  • VS Code
  • IntelliJ IDEA
  • Microsoft Word
  • Photoshop

Infix, Prefix and Postfix Expressions


Infix

Operators appear between operands.

Example:

A + B

Prefix

Operator appears before operands.

Example:

+ A B

Postfix

Operator appears after operands.

Example:

A B +

Stacks are heavily used to convert and evaluate these expressions.


Balanced Parentheses Problem

Problem

Determine whether an expression contains balanced brackets.

Example:

({[]})

Valid

({[})

Invalid


Solution Using Stack

Algorithm

  1. Push opening brackets.
  2. For closing brackets:

Check stack top. Match pair.

  1. Continue.
  2. Stack must be empty at the end.

Java Example

import java.util.Stack;

public static boolean isBalanced(String s) {

    Stack<Character> stack = new Stack<>();

    for(char ch : s.toCharArray()) {

        if(ch == '(' || ch == '{' || ch == '[') {
            stack.push(ch);
        }
        else {

            if(stack.isEmpty())
                return false;

            char top = stack.pop();

            if((ch == ')' && top != '(') ||
               (ch == '}' && top != '{') ||
               (ch == ']' && top != '['))
                return false;
        }
    }

    return stack.isEmpty();
}

Time Complexity:

O(n)

Space Complexity:

O(n)

Advantages of Stack

  • Simple to implement
  • Fast insertion and deletion
  • Efficient memory usage
  • Supports recursion naturally
  • Useful in many real-world applications

Disadvantages of Stack

  • Limited access to elements
  • Cannot directly access middle elements
  • Fixed-size arrays may overflow

Interview Questions on Stack

Easy

  1. Implement Stack Using Array
  2. Implement Stack Using Linked List
  3. Reverse a String Using Stack
  4. Balanced Parentheses

Medium

  1. Next Greater Element
  2. Min Stack
  3. Evaluate Postfix Expression
  4. Stock Span Problem

Hard

  1. Largest Rectangle in Histogram
  2. Trapping Rain Water
  3. Sliding Window Maximum
  4. Expression Conversion Problems

Summary

A Stack is a linear data structure that follows the Last In First Out (LIFO) principle.

Key Operations

OperationDescription
PushInsert Element
PopRemove Element
PeekView Top Element
isEmptyCheck Empty Stack
SizeCount Elements

Complexity

OperationComplexity
PushO(1)
PopO(1)
PeekO(1)
isEmptyO(1)

Common Applications

  • Function Calls
  • Recursion
  • Browser History
  • Undo/Redo Operations
  • Expression Evaluation
  • Balanced Parentheses Checking

Stack is one of the most important data structures in DSA and serves as the foundation for many advanced algorithms and interview problems.