






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







How to use this guide. Every program here was run with Python 3, and the output under each one is its real output. Save a block as a .py file and run python3 file.py to try it. Read Section 1 on Big-O first, because every later section uses it.
Contents
Big-O notation Arrays and searching Linked lists Stacks Queues (including circular queues) Trees and binary search trees Sorting algorithms Summary table Practice questions and answers
Big-O describes how an algorithm's running time (or memory) grows as the input size n grows. It ignores constant factors and smaller terms, because for large n the fastest-growing term dominates. For example, 3n² + 5n + 20 is O(n²).
Big-O Name Example operation O(1) Constant (^) Read a[i] from an array; push onto a stack O(log n) Logarithmic Binary search; search in a balanced BST O(n) Linear Linear search; traverse a linked list O(n log n) Linearithmic Merge sort; average quick sort O(n²) Quadratic Bubble, selection, insertion sort; nested loops over the same data O(2ⁿ) Exponential Trying every subset of n items
How fast do these grow?
import math
print(f"{'n':>7} {'log2 n':>7} {'n log2 n':>10} {'n^2':>14}") for n in [10, 100, 1000, 10**6]: print(f"{n:>7} {math.log2(n):>7.1f} {n * math.log2(n):>10.0f} {n * n:>14}")
def count_pairs(items): """Nested loops: about n*(n-1)/2 comparisons, so O(n^2).""" comparisons = 0 for i in range(len(items)): for j in range(i + 1, len(items)): comparisons += 1 return comparisons
print("comparisons for n=100:", count_pairs(range(100)))
n log2 n n log2 n n^ 10 3.3 33 100 100 6.6 664 10000 1000 10.0 9966 1000000 1000000 19.9 19931569 1000000000000 comparisons for n=100: 4950
At n = 1,000,000, an O(n log n) algorithm does about 20 million steps while an O(n²) one does a trillion. That is the practical reason merge sort beats bubble sort on large data.
Rules for working out Big-O from code
A simple statement is O(1). A loop that runs n times around O(1) work is O(n). Nested loops multiply: n × n = O(n²). The pairs loop above does n(n − 1)/2 = 100 × 99 / 2 = 4,950 comparisons, still O(n²). Sequential blocks add, and you keep the largest: O(n) + O(n²) = O(n²). A loop that halves the problem each time is O(log n). Best, average and worst case can differ. Unless stated otherwise, Big-O usually refers to the worst case. Space complexity measures extra memory the same way. Merge sort needs O(n) extra space; insertion sort needs O(1).
2. Arrays and searching
An array stores elements in contiguous memory, so element i can be found directly from its address: O(1) random access. Inserting or deleting in the middle is O(n) because later elements must shift. A Python list is a dynamic array: append is O(1) on average (amortised), insert(0, x) is O(n).
Linear search checks each element in turn: O(n), works on unsorted data. Binary search needs sorted data and halves the search range each step: O(log n).
def linear_search(items, target): """Return the index of target, or -1. O(n).""" for i, value in enumerate(items): if value == target: return i return -
def binary_search(items, target): """items must be sorted. Return (index or -1, steps taken). O(log n).""" low, high = 0, len(items) - 1 steps = 0 while low <= high: steps += 1 mid = (low + high) // 2 if items[mid] == target: return mid, steps elif items[mid] < target: low = mid + 1 # discard the left half else: high = mid - 1 # discard the right half return -1, steps
marks = [12, 25, 31, 47, 58, 63, 77, 82, 90, 96] print("linear_search(77):", linear_search(marks, 77)) print("binary_search(77):", binary_search(marks, 77)) print("binary_search(40):", binary_search(marks, 40))
self.head = self.head.next return True prev = self.head while prev.next is not None: if prev.next.data == data: prev.next = prev.next.next # bypass the node return True prev = prev.next return False
def reverse(self): # O(n), in place prev, current = None, self.head while current is not None: nxt = current.next current.next = prev prev, current = current, nxt self.head = prev
def str(self): parts, current = [], self.head while current is not None: parts.append(str(current.data)) current = current.next return " -> ".join(parts) + " -> None"
ll = LinkedList() for x in [20, 30, 40]: ll.append(x) ll.push_front(10) print(ll) print("delete 30:", ll.delete(30), "|", ll) print("delete 99:", ll.delete(99)) ll.reverse() print("reversed:", ll)
10 -> 20 -> 30 -> 40 -> None delete 30: True | 10 -> 20 -> 40 -> None delete 99: False reversed: 40 -> 20 -> 10 -> None
How reverse works. Walk through the list once, turning each next pointer around so it points to the previous node. Three references are needed: prev , current and nxt (saved before the pointer is changed so the rest of the list is not lost).
Operation Array (Python list) Singly linked list Access element i O(1) O(n) Insert / delete at front O(n) O(1) Insert at end O(1) amortised O(n) without a tail pointer, O(1) with one Delete a given value O(n) O(n) (search) Memory Compact, may over-allocate Extra pointer per node
4. Stacks
A stack is LIFO (Last In, First Out): the last item pushed is the first popped, like a pile of plates. Operations: push , pop , peek (look at the top), is_empty , each O(1). Uses: function call stack, undo, back button, expression evaluation, bracket checking, depth-first search.
from collections import deque
class Stack: """LIFO stack on a Python list; push and pop at the end are O(1).""" def init(self): self._items = []
def push(self, item): self._items.append(item)
def pop(self): if self.is_empty(): raise IndexError("pop from empty stack") return self._items.pop()
def peek(self): return self._items[-1]
def is_empty(self): return len(self._items) == 0
def is_balanced(expr): pairs = {")": "(", "]": "[", "}": "{"} s = Stack() for ch in expr: if ch in "([{": s.push(ch) elif ch in pairs: if s.is_empty() or s.pop() != pairs[ch]: return False return s.is_empty()
for e in ["{[a+b]*(c-d)}", "(a+b]", "((x)"]: print(f"{e!r:16} balanced? {is_balanced(e)}")
q = deque() for customer in ["Amina", "Brian", "Carol"]: q.append(customer) # enqueue at the rear print("served:", q.popleft()) # dequeue from the front q.append("David") print("queue now:", list(q))
class CircularQueue: """Fixed-size queue in an array; front and rear wrap around with %.""" def init(self, capacity): self.data = [None] * capacity self.capacity = capacity self.front = 0 self.size = 0
def enqueue(self, item): if self.size == self.capacity: raise OverflowError("queue full") rear = (self.front + self.size) % self.capacity self.data[rear] = item self.size += 1
def dequeue(self): if self.size == 0: raise IndexError("queue empty") item = self.data[self.front]
def insert(root, key): """Insert key into a binary search tree and return the root.""" if root is None: return TreeNode(key) if key < root.key: root.left = insert(root.left, key) elif key > root.key: root.right = insert(root.right, key) return root # duplicates are ignored
def search(root, key): while root is not None and root.key != key: root = root.left if key < root.key else root.right return root is not None
def inorder(n): return inorder(n.left) + [n.key] + inorder(n.right) if n else [] def preorder(n): return [n.key] + preorder(n.left) + preorder(n.right) if n else [] def postorder(n): return postorder(n.left) + postorder(n.right) + [n.key] if n else []
def height(n): """Height in edges: a single node has height 0, an empty tree -1.""" return -1 if n is None else 1 + max(height(n.left), height(n.right))
root = None for k in [50, 30, 70, 20, 40, 60, 80, 35]: root = insert(root, k)
print("inorder: ", inorder(root)) print("preorder: ", preorder(root)) print("postorder:", postorder(root)) print("height:", height(root)) print("search 60:", search(root, 60), "| search 65:", search(root, 65))
inorder: [20, 30, 35, 40, 50, 60, 70, 80] preorder: [50, 30, 20, 40, 35, 70, 60, 80] postorder: [20, 35, 40, 30, 60, 80, 70, 50] height: 3 search 60: True | search 65: False
The tree built by inserting 50, 30, 70, 20, 40, 60, 80, 35:
50 / 30 70 / \ / 20 40 60 80 / 35
Traversal Order Result Typical use Inorder Left, Node, Right 20 30 35 40 50 60 70 80 Gives a BST's keys in sorted order Preorder Node, Left, Right 50 30 20 40 35 70 60 80 Copying a tree; prefix expressions Postorder Left, Right, Node 20 35 40 30 60 80 70 50 Deleting a tree; postfix expressions Level order Level by level (uses a queue) 50 30 70 20 40 60 80 35 Breadth-first processing
The height is 3 (path 50 → 30 → 40 → 35). Deleting from a BST has three cases: a leaf is simply removed; a node with one child is replaced by that child; a node with two children is replaced by its inorder successor (smallest key in its right subtree), which is then deleted from there.
7. Sorting algorithms
def bubble_sort(a): a = a[:] n = len(a) for i in range(n - 1): swapped = False for j in range(n - 1 - i): # largest item "bubbles" to the end if a[j] > a[j + 1]: a[j], a[j + 1] = a[j + 1], a[j] swapped = True if not swapped: # already sorted: stop early break return a
def selection_sort(a): a = a[:] for i in range(len(a) - 1): smallest = i for j in range(i + 1, len(a)): if a[j] < a[smallest]: smallest = j a[i], a[smallest] = a[smallest], a[i] return a
def insertion_sort(a): a = a[:] for i in range(1, len(a)): key, j = a[i], i - 1 while j >= 0 and a[j] > key: # shift bigger items right a[j + 1] = a[j] j -= 1 a[j + 1] = key return a
def merge_sort(a): if len(a) <= 1: return a mid = len(a) // 2 left, right = merge_sort(a[:mid]), merge_sort(a[mid:]) merged, i, j = [], 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: # <= keeps the sort stable merged.append(left[i]); i += 1 else: merged.append(right[j]); j += 1 return merged + left[i:] + right[j:]
def quick_sort(a): if len(a) <= 1: return a pivot = a[len(a) // 2] less = [x for x in a if x < pivot] equal = [x for x in a if x == pivot] greater = [x for x in a if x > pivot] return quick_sort(less) + equal + quick_sort(greater)
data = [64, 25, 12, 22, 11, 90, 45]
Structure Rule / shape Key operations and cost Typical uses
Stack LIFO push, pop, peek O(1) Undo, call stack, bracket matching, postfix evaluation
Queue FIFO enqueue, dequeue O(1) (deque or circular array)
Scheduling, buffering, BFS
Priority queue / heap
Highest priority first
insert, remove-top O(log n); peek O(1)
Task scheduling, Dijkstra's algorithm
Binary search tree left < node < right search, insert, delete O(h): O(log n) balanced, O(n) worst
Ordered data, range queries
Hash table (Python dict)
Key → bucket by hash
insert, lookup, delete O(1) average Fast lookups by key
Binary search Sorted data, halve each step
O(log n) Searching sorted arrays
Merge / quick sort Divide and conquer O(n log n) (quick sort worst O(n²)) General-purpose sorting
Bubble / selection / insertion
Simple comparison sorts
O(n²) Small or nearly sorted data, teaching
9. Practice questions
What is the Big-O of 3n² + 10n + 7? Explain why the other terms are dropped. State the Big-O of: (a) reading a[500] , (b) a loop inside a loop over the same n items, (c) a loop where i doubles each time until it reaches n. Why is binary search not suitable for an unsorted list? What is the maximum number of comparisons binary search needs for 1,000,000 sorted items? Give two advantages of a linked list over an array, and one disadvantage. Write a Python method count() for the LinkedList class that returns the number of nodes. What is the difference between a stack and a queue? Give one real-world use of each. Evaluate the postfix expression 6 2 3 + * 4 - using a stack, showing the stack after each step. Why should you use collections.deque rather than a list for a queue in Python? In a circular queue of capacity 5 with front = 3 and size = 4 , at which index is the next item stored? Insert 40, 20, 60, 10, 30, 50, 70, 25 into an empty BST. Give the inorder, preorder and postorder traversals. What is the height of the tree in question 11? When does a BST degrade to O(n) search, and how can this be prevented? Describe how to delete a node with two children from a BST. Show the list after each pass of insertion sort on [29, 10, 14, 37, 13]. Show the list after each pass of selection sort on [29, 10, 14, 37, 13]. Why is merge sort O(n log n) in every case? What causes quick sort's worst case, and how can it be avoided? What does it mean for a sorting algorithm to be stable? Name two stable sorts. Which data structure would you choose for each, and why? (a) undo in a text editor, (b) customers waiting for a cashier, (c) looking up a student by ID number, (d) keeping data always in sorted order with fast insertion.
Answers
1. O(n²). For large n, n² grows much faster than n, and constants (3, 10, 7) do not change the growth rate, so only the dominant term is kept. 2. (a) O(1). (b) O(n²). (c) O(log n), because the number of doublings from 1 to n is about log₂ n. 3. Binary search decides which half to discard by comparing with the middle item. That only works if all smaller items are on one side and all larger items on the other, which is true only for sorted data. 4. ⌊log₂ 1,000,000⌋ + 1 = 19 + 1 = 20 comparisons (2²⁰ = 1,048,576 ≥ 1,000,000). 5. Advantages: O(1) insertion and deletion at the head (no shifting); grows one node at a time with no need for a contiguous block or resizing. Disadvantage: no random access (finding item i is O(n)), plus extra memory for pointers.
6.
def count(self): total, current = 0, self.head while current is not None: total += 1 current = current.next return total
7. A stack is LIFO (remove the newest item); a queue is FIFO (remove the oldest item). Stack: the browser back button. Queue: documents waiting at a printer. 8. Push 6 → [6]; push 2 → [6, 2]; push 3 → [6, 2, 3]; + → [6, 5]; * → [30]; push 4 → [30, 4]; - → [26]. Result 26.