Algorithms
Table of Contents
A finite, unambiguous sequence of steps that transforms input into output to solve a well-defined problem. The correctness, efficiency, and resource usage of an algorithm determine whether a solution is practical at scale.
Related: Data Structures Big O Notation Software Design Patterns
Complexity
Algorithm performance is described in terms of how it scales with input size n. See Big O Notation for the full reference.
| Complexity | Name | Example |
|---|---|---|
| O(1) | Constant | Hash table lookup |
| O(log n) | Logarithmic | Binary search |
| O(n) | Linear | Linear search |
| O(n log n) | Linearithmic | Merge sort, heap sort |
| O(n²) | Quadratic | Bubble sort, insertion sort |
| O(2ⁿ) | Exponential | Brute-force subset enumeration |
Sorting
Comparison sorts
# Python built-in — Timsort, O(n log n), stable sorted([3, 1, 4, 1, 5]) [3, 1, 4].sort() # in-place # Key function sorted(words, key=str.lower) sorted(people, key=lambda p: (p.surname, p.firstname)) # Reverse sorted(numbers, reverse=True)
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Timsort | O(n) | O(n log n) | O(n log n) | O(n) | 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²) | O(log n) | No |
| Heap sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Bubble sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
Use Python's built-in sorted() / list.sort() — Timsort is
optimal for real-world data. Implement sorting algorithms only
when studying or when specific properties are needed.
Searching
Linear search — O(n)
Check each element in sequence. Works on unsorted data.
def linear_search(lst, target): for i, item in enumerate(lst): if item == target: return i return -1
Binary search — O(log n)
Requires sorted data. Halves the search space each step.
import bisect # bisect — standard library binary search sorted_list = [1, 3, 5, 7, 9] bisect.bisect_left(sorted_list, 5) # index where 5 would be inserted → 2 # Manual implementation def binary_search(lst, target): lo, hi = 0, len(lst) - 1 while lo <= hi: mid = (lo + hi) // 2 if lst[mid] == target: return mid elif lst[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1
Graph Algorithms
Graphs are used to model networks, paths, dependencies, and relationships.
Breadth-First Search (BFS) — O(V + E)
Explores neighbours level by level. Finds shortest path in unweighted graphs.
from collections import deque def bfs(graph, start): visited = set() queue = deque([start]) visited.add(start) order = [] while queue: node = queue.popleft() order.append(node) for neighbour in graph[node]: if neighbour not in visited: visited.add(neighbour) queue.append(neighbour) return order graph = {0: [1, 2], 1: [3], 2: [3], 3: []} bfs(graph, 0) # [0, 1, 2, 3]
Depth-First Search (DFS) — O(V + E)
Explores as far as possible down each branch before backtracking. Used for cycle detection, topological sort, pathfinding.
def dfs(graph, start, visited=None): if visited is None: visited = set() visited.add(start) for neighbour in graph[start]: if neighbour not in visited: dfs(graph, neighbour, visited) return visited
Dijkstra's — O((V + E) log V)
Shortest path in a weighted graph with non-negative weights.
import heapq def dijkstra(graph, start): distances = {node: float('inf') for node in graph} distances[start] = 0 heap = [(0, start)] while heap: dist, node = heapq.heappop(heap) if dist > distances[node]: continue for neighbour, weight in graph[node].items(): new_dist = dist + weight if new_dist < distances[neighbour]: distances[neighbour] = new_dist heapq.heappush(heap, (new_dist, neighbour)) return distances graph = { 'A': {'B': 1, 'C': 4}, 'B': {'C': 2, 'D': 5}, 'C': {'D': 1}, 'D': {} } dijkstra(graph, 'A') # {'A': 0, 'B': 1, 'C': 3, 'D': 4}
Dynamic Programming
Optimises recursive problems by storing results of subproblems (memoisation or tabulation). Applicable when problems have overlapping subproblems and optimal substructure.
# Fibonacci — naive O(2ⁿ) def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2) # Memoisation — O(n) from functools import lru_cache @lru_cache(maxsize=None) def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2) # Tabulation — O(n), no recursion def fib(n): if n <= 1: return n dp = [0, 1] for i in range(2, n + 1): dp.append(dp[-1] + dp[-2]) return dp[n]
Two Pointers and Sliding Window
Common patterns in array/string problems that achieve O(n) where a naive approach is O(n²).
# Two pointers — find pair summing to target in sorted array def two_sum_sorted(arr, target): lo, hi = 0, len(arr) - 1 while lo < hi: s = arr[lo] + arr[hi] if s == target: return (lo, hi) elif s < target: lo += 1 else: hi -= 1 return None # Sliding window — max sum subarray of size k def max_subarray(arr, k): window_sum = sum(arr[:k]) best = window_sum for i in range(k, len(arr)): window_sum += arr[i] - arr[i - k] best = max(best, window_sum) return best
Tips
- Know the complexity of Python built-ins:
inon a list is O(n), on a set/dict is O(1);list.appendis amortised O(1);list.insert(0, x)is O(n) - Use
heapqfor priority queues — Python has no built-in heap class butheapqmodule operates on a plain list collections.dequeis O(1) for both ends;listis O(1) for the right end but O(n) for the left — usedequefor queues- For graph problems: BFS = shortest path (unweighted), DFS = exhaustive search / cycle detection, Dijkstra = shortest path (weighted, non-negative)
@lru_cacheis the fastest way to add memoisation in Python — one decorator line converts an exponential naive solution to linear