Download The Complete Data Structures & Algorithms (DSA) Beginner's Course Guide and more Study notes Data Structures and Algorithms in PDF only on Docsity!
Data Structures
& Algorithms
The Complete Beginner's Course Guide
Arrays · Linked Lists · Stacks · Queues · Trees · Graphs
Sorting · Searching · Recursion · Dynamic Programming · Big-O Notation
Beginner Friendly Edition | 2025
Table of Contents
Ch 1: Why DSA? Big-O & Complexity
› What is DSA?
› Why learn it?
› Big-O Notation explained
› Time vs Space
Ch 2: Arrays – The Foundation
› What is an Array?
› Operations
› Multi-dimensional arrays
› Real-life examples
Ch 3: Linked Lists – Chains of Data
› Singly Linked List
› Doubly Linked List
› Insert/Delete operations
› vs Arrays
Ch 4: Stacks & Queues
› Stack: LIFO concept
› Queue: FIFO concept
› Real-life analogies
› Code examples
Ch 5: Trees – Hierarchical Data
› Binary Trees
› Binary Search Trees
› Tree Traversals
› Real-life: File systems
Ch 6: Graphs – Networks of Data
› What is a Graph?
› BFS & DFS
› Real-life: Maps, Social networks
Ch 7: Sorting Algorithms
› Bubble, Selection, Insertion
› Merge Sort & Quick Sort
› Comparison table
Chapte
r 1 Why DSA? Big-O & Complexity
Understanding how fast and efficient your code is
1.1 What is DSA?
Data Structures are ways of organising and storing data so it can be accessed and modified
efficiently. Algorithms are step-by-step instructions to solve a problem. Together, DSA is the
backbone of every program ever written.
n Real Life: A Library
A library has thousands of books. If books were thrown randomly on the floor (no data
structure), finding one book could take hours.
But books are organised by genre, then author, then title (a data structure). And the process of
finding a book — check genre section, scan authors, pick title — is an algorithm. Together
they make finding a book fast and easy!
1.2 Why Learn DSA?
- Crack Tech Interviews — Google, Amazon, Microsoft, Meta all test DSA heavily.
- Write Faster Code — The right data structure can make code 1000x faster.
- Solve Hard Problems — DSA gives you tools to tackle complex real-world problems.
- Understand Frameworks — React, Django, databases — all built on DSA concepts.
- Think Like a Programmer — DSA trains your brain to break problems into steps.
1.3 Big-O Notation – How Fast Is Your Code?
Big-O notation describes how the time or memory of an algorithm grows as the input size (n)
increases. It helps us compare algorithms fairly regardless of hardware. We always analyse the
worst case.
n Real Life: Finding a Name in a Phone Book
O(1) — Constant: You know exactly where the name is (pg 47). Always takes the same time
no matter how big the book.
O(log n) — Logarithmic: You open the middle, decide left or right, repeat. (Binary search!) —
Very fast even for huge books.
O(n) — Linear: You read every name from page 1 until you find it. Doubles the time if the
book doubles in size.
O(n^2) — Quadratic: For each name, you check every other name. Gets very slow very fast!
Big-O Name Speed Example n=1000 operations
O(1) Constant Instant Array index access 1
O(log n) Logarithmic Very Fast Binary Search ~
O(n) Linear Fast Linear Search 1,
O(n log n) Linearithmic Good Merge Sort ~10,
O(n^2) Quadratic Slow Bubble Sort 1,000,
O(2^n) Exponential Very Slow Brute Force Astronomical
O(n!) Factorial Terrible Permutations Impossible
n Tip: Always aim for O(1) or O(log n). O(n) is acceptable. Avoid O(n^2) for large datasets — it
will be too slow!
marks.remove(99) # Remove first occurrence of 99
Search – O(n) worst case
print(88 in marks) # True
Iterate – O(n)
for mark in marks: print(mark)
Length
print(len(marks)) # Number of elements
Slicing – create subarray
first_three = marks[0:3] # [85, 78, 95]
2D Array (matrix) – like a spreadsheet grid
grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(grid[1][2]) # Row 1, Col 2 → 6
Operation Time Complexity Space Notes
Access by index O(1) O(1) Instant – direct memory jump
Search (linear) O(n) O(1) Check each element one by one
Insert at end O(1)* O(1) *Amortised; O(n) when resizing
Insert at index O(n) O(1) Must shift all elements right
Delete at end O(1) O(1) Just shrink the size
Delete at index O(n) O(1) Must shift all elements left
n Tip: Arrays are perfect when you know the size upfront and need fast access by position. For
frequent insertions/deletions, consider Linked Lists.
Chapte
r 3 Linked Lists – Chains of Data
Dynamic structures that grow and shrink freely
3.1 What is a Linked List?
A linked list is a sequence of nodes , where each node stores data and a pointer (link) to the
next node. Unlike arrays, elements are not stored in contiguous memory — they can be
anywhere, connected by pointers.
n Real Life: A Treasure Hunt
In a treasure hunt, the first clue tells you where to find clue 2. Clue 2 points to clue 3. Clue 3
points to the treasure. Each clue = a node (data + pointer to next). You MUST start from clue 1
— you can't jump directly to clue 4!
Other examples: a train (each carriage links to the next), a music playlist (each song links to
the next), browser history.
Node Structure:
DATA NEXT
3.2 Singly Linked List in Python
A single Node
class Node: def init(self, data): self.data = data # The value stored self.next = None # Pointer to next node (None = end)
The Linked List
class LinkedList: def init(self): self.head = None # Start of the list
def append(self, data): # Add to END – O(n) new_node = Node(data) if not self.head: self.head = new_node return current = self.head while current.next: # Walk to the last node current = current.next
Memory usage Less (no pointers) More (stores pointers)
Best for Random access Frequent insert/delete
n Tip: Use Arrays when you need fast access by index. Use Linked Lists when you frequently
add/remove from the front or middle.
Chapte
r 4 Stacks & Queues
LIFO and FIFO – essential in everyday computing
4.1 Stack – Last In, First Out (LIFO)
A stack is like a pile — you can only add or remove from the top. The last item placed is the first
one taken out. Think of it like a stack of plates.
n Real Life: Stack of Plates
At a canteen, clean plates are stacked. When you take a plate, you take the TOP one (the last
one placed). When a plate is added, it goes on TOP. You can never take a plate from the
middle or bottom!
Computer uses: Undo/Redo in editors, browser Back button, function call stack, expression
evaluation, syntax checking.
Stack using Python list
class Stack: def init(self): self.items = []
def push(self, item): # Add to top – O(1) self.items.append(item) print(f'Pushed: {item}')
def pop(self): # Remove from top – O(1) if self.is_empty(): return 'Stack is empty!' return self.items.pop()
def peek(self): # See top without removing – O(1) if self.is_empty(): return 'Stack is empty!' return self.items[-1]
def is_empty(self): return len(self.items) == 0
def size(self): return len(self.items)
Real-world: Undo feature simulation
undo_stack = Stack() undo_stack.push('Type Hello') # User types undo_stack.push('Bold text') # User bolds
print(printer.front()) # Photo.png is next
Feature Stack (LIFO) Queue (FIFO)
Order Last In, First Out First In, First Out
Add push() to TOP enqueue() to BACK
Remove pop() from TOP dequeue() from FRONT
Real life Plate stack, Undo Ticket line, Print queue
Use in CS Function calls, DFS BFS, Scheduling, Buffers
n Tip: Python's collections.deque is perfect for queues — O(1) append and popleft. Never use a
regular list for queues (popleft on a list is O(n)!).
Chapte
r 5 Trees – Hierarchical Data
Non-linear structures for parent-child relationships
5.1 What is a Tree?
A tree is a hierarchical data structure with a root node at the top, connected to child nodes ,
which have their own children, and so on. Unlike arrays or linked lists, trees branch out in
multiple directions.
n Real Life: Family Tree
Your family tree has grandparents at the top (root), then parents (children of root), then you
and your siblings (children of parents), etc.
Other real-life trees: Company org chart (CEO at top, managers below, employees at leaves),
File system folders (root drive, then folders, then files), HTML DOM structure of a web page.
Key Tree Terminology:
- Root: The topmost node — has no parent. Like the CEO of a company.
- Parent: A node that has children below it.
- Child: A node connected below a parent.
- Leaf: A node with NO children — the end of a branch.
- Height: The number of edges from root to the deepest leaf.
- Depth: Distance from the root to a specific node.
- Subtree: A node and all its descendants.
5.2 Binary Search Tree (BST)
A Binary Search Tree is a tree where each node has at most 2 children. The key rule: left
child < parent < right child. This ordering makes searching very fast — O(log n) on average!
n Real Life: Dictionary Search
A BST is like searching in a dictionary. Open to the middle page. Is your word before or after?
Go left (before) or right (after). Repeat. You eliminate HALF the remaining pages each time —
that's O(log n)!
class TreeNode: def init(self, val): self.val = val self.left = None # Left child
Level-order Level by level BFS on tree 50 | 30 70 | 20 40
n Tip: In-order traversal of a BST always gives elements in sorted order. This is a very common
interview question!
Chapte
r 6 Graphs – Networks of Data
The most powerful and versatile data structure
6.1 What is a Graph?
A graph is a collection of nodes (vertices) connected by edges. Unlike trees, graphs can have
cycles and nodes can connect to ANY other node. Graphs model anything that involves
connections and relationships.
n Real Life: Social Network
On Instagram, each user is a node. A 'follow' is a directed edge. When you follow Ali, there's
an arrow from you to Ali.
Google Maps is a graph: cities are nodes, roads are edges, and the distance/time is the edge
weight. Finding the shortest route is a graph algorithm!
Also: Internet (devices + cables), airline routes, electrical circuits, WhatsApp group chats,
recommendation engines (Netflix suggests because your node connects to similar-taste
nodes).
Type Description Example
Undirected Edges go both ways Facebook friends (mutual)
Directed Edges have direction Instagram follow, Twitter
Weighted Edges have a cost/value Google Maps (distance)
Cyclic Contains loops/cycles Road network with roundabouts
Acyclic No cycles (DAG) Task dependency (do A before B)
6.2 Graph Representation
Adjacency List – most common representation
graph = { 'Karachi': ['Hyderabad', 'Sukkur'], 'Hyderabad':['Karachi', 'Nawabshah'], 'Sukkur': ['Karachi', 'Larkana'], 'Nawabshah':['Hyderabad'], 'Larkana': ['Sukkur'] }
BFS – Breadth First Search
Explores level by level (like ripples in water)
Chapte
r 7 Sorting Algorithms
Arranging data in order — one of CS's most studied problems
7.1 Bubble Sort – The Simplest Sort
Bubble sort repeatedly compares adjacent elements and swaps them if they're in the wrong
order. Large elements 'bubble' to the end. It's simple but slow — O(n^2) — only good for very
small datasets or teaching.
n Real Life: Sorting People by Height
Line up 5 people randomly. Walk along the line comparing adjacent pairs. If person on left is
taller, swap them. After one full pass, the tallest person is at the end. Repeat for remaining
people. Simple but takes many passes!
def bubble_sort(arr): n = len(arr) for i in range(n): swapped = False for j in range(0, n-i-1): # Last i elements already sorted if arr[j] > arr[j+1]: # Compare adjacent arr[j], arr[j+1] = arr[j+1], arr[j] # Swap! swapped = True if not swapped: # Already sorted – early exit break return arr
nums = [64, 34, 25, 12, 22, 11, 90] print(bubble_sort(nums)) # [11, 12, 22, 25, 34, 64, 90]
7.2 Merge Sort – Divide and Conquer
Merge sort splits the array in half recursively until each piece has 1 element, then merges them
back in sorted order. It's O(n log n) — much faster than bubble sort! Python's built-in sort uses a
variant of merge sort.
n Real Life: Sorting Exam Papers
You have 16 papers to sort by name. Give 8 to friend A, 8 to friend B. They each split further
and sort their half. Then you merge the two sorted halves into one sorted pile. Dividing the
work makes it much faster!
def merge_sort(arr): if len(arr) <= 1:
return arr # Base case: 1 element is already sorted
mid = len(arr) // 2 left = merge_sort(arr[:mid]) # Sort left half right = merge_sort(arr[mid:]) # Sort right half return merge(left, right) # Merge them
def merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]); i += 1 else: result.append(right[j]); j += 1 result.extend(left[i:]) # Add remaining result.extend(right[j:]) return result
nums = [38, 27, 43, 3, 9, 82, 10] print(merge_sort(nums)) # [3, 9, 10, 27, 38, 43, 82]
7.3 Sorting Algorithm Comparison
Algorithm Best Case Average Worst Case Space Stable?
Bubble Sort O(n) O(n^2) O(n^2) O(1) Yes
Selection Sort O(n^2) O(n^2) O(n^2) O(1) No
Insertion Sort O(n) O(n^2) O(n^2) O(1) Yes
Merge Sort O(n log n) O(n log n) O(n log n) O(n) Yes
Quick Sort O(n log n) O(n log n) O(n^2) O(log n) No
Python sorted() O(n) O(n log n) O(n log n) O(n) Yes
n Tip: In real projects, always use Python's built-in sorted() or list.sort(). They use Timsort — a
highly optimised hybrid algorithm. Only implement sorting manually in interviews!