Notes – Stack in DSA

What is a Stack?

  • A Stack is a linear data structure that follows the LIFO principle:
    Last In, First Out
  • The last element added is the first one to be removed.

Real-Life Examples

  • Stack of plates: You remove the top plate first.
  • Undo feature in editors: Recent changes are undone first.
  • Browser back button: Stores the most recent page on top.

Basic Stack Operations


OperationDescription
push()Add an element to the top of the stack
pop()Remove and return the top element
peek() / top()View the top element without removing it
isEmpty()Check if the stack is empty

Stack Implementation

Stacks can be implemented in two ways:

  • Using Arrays
  • Using Linked Lists

Time Complexity


OperationTime Complexity
pushO(1)
popO(1)
peekO(1)

All stack operations are constant time, which makes them very efficient.


Applications of Stack

  • Expression evaluation (Infix, Prefix, Postfix)
  • Function call handling (Call Stack)
  • Backtracking algorithms (Maze, Recursion)
  • Syntax parsing (compilers)