Data Structure and Algorithms – Stacks

Resources:

1. What is Stack?

A Stack is one of the most fundamental linear data structures in computer science. If you’ve ever piled up a stack of cafeteria trays or used the “Undo” button in a text editor, you’ve already interacted with a stack in the real world.

A stack is a linear data structure that follows the LIFO (Last-In, First-Out) principle. This means the last element added to the stack is the first one to be removed. Think of it like a stack of books: you place a new book on top, and if you want to take one out, you take the one from the top first.

2. Core Operations of a Stack

To be considered a stack, a data structure must support these primary operations:

  1. Push: Adds an element to the top of the stack.
  2. Pop: Removes the topmost element from the stack.
  3. Peek (or Top): Returns the value of the top element without removing it.
  4. isEmpty: Checks if the stack is empty.
  5. isFull: (In fixed-size arrays) Checks if the stack has reached its capacity.

3. How it Works?

The stack maintains a pointer (often called top) that keeps track of the index of the last element added.

  • When you Push, the top pointer increments, and the new element is placed at that position.
  • When you Pop, the element at the top is removed (or returned), and the top pointer decrements.

4. Complexity Analysis

Because we only ever interact with the “top” of the data structure, stacks are incredibly efficient:

  • Time Complexity: All basic operations (Push, Pop, Peek) are O(1).
  • Space Complexity: O(n), where n is the number of elements stored.

5. Real-World Applications

  • Function Calls (The Call Stack): Modern programming languages use a stack to manage active functions. When a function is called, it’s pushed onto the stack; when it finishes, it’s popped.
  • Expression Evaluation: Used by compilers to evaluate mathematical expressions (like converting Infix to Postfix).
  • Backtracking: Used in algorithms to solve puzzles like mazes or the N-Queens problem.
  • Undo/Redo: Your browser history and text editors use stacks to track your previous states.

6. Code Implementation

Github Link: https://github.com/computingnotes/DataStructureAndAlgorithms/blob/main/DSA_Stacks.ipynb

Leave a Reply

Your email address will not be published. Required fields are marked *

error: