Algorithms Tutorial: Big O, Sorting, Graphs and Dynamic Programming in Python

Development 31 min readUpdated Oct 30, 2026
5 views0 comments

An algorithm is a precise list of steps that solves a problem. A recipe is an algorithm for making a meal; the way you look up a name in a phone book is an algorithm for finding a person. In programming, the same problem can usually be solved in many ways, and the difference between a good and a bad choice can be enormous: one method might answer in a blink, while another would need hours or run out of memory on the same data. Learning algorithms teaches you to see that difference, and gives you a toolbox of proven methods, so you do not have to invent them under pressure.

This tutorial takes you from zero to a solid foundation. We start with how to measure how fast an algorithm is, then move through searching, sorting, recursion, graphs, greedy methods and dynamic programming. All examples are in Python because it reads almost like pseudocode, so you can focus on the idea instead of the syntax. Every example was run and tested before publishing, and you can copy it straight into a file. If you want to refresh the language first, see Python Virtual Environments Explained to set up a clean environment.

How to use this tutorial: do not just read it. Type each example, change it, break it and run it again. Algorithms are learned with your fingers. The last section gives a practice plan.

Contents

1. How to measure an algorithm: Big O

You could time a program with a stopwatch, but the result depends on your computer, your Python version and what else is running. Computer scientists use a better yardstick: how much the work grows when the input grows. We call the input size n (for example, the number of items in a list), and we describe the growth with Big O notation.

Big O answers the question: “If I make the input ten times bigger, how much slower does this get?” It ignores small details (a constant factor, a few extra steps) and keeps only the part that dominates when n is large.

The common growth rates

Big O Name If n = 1,000 (rough number of steps) Example
O(1) Constant 1 Read one item by its index, look up a key in a dictionary
O(log n) Logarithmic 10 Binary search in a sorted list
O(n) Linear 1,000 Look through every item once
O(n log n) Linearithmic 10,000 Good sorting algorithms (merge sort, Python’s sorted)
O(n²) Quadratic 1,000,000 Compare every item with every other (nested loops)
O(2ⁿ) Exponential about 10³⁰¹ Trying every subset; naive recursive Fibonacci
O(n!) Factorial unimaginably large Trying every ordering of the items

The difference is dramatic. With a million items, a linear algorithm needs about a million steps and finishes in a fraction of a second. A quadratic one needs a trillion steps, which takes hours. An exponential one never finishes in your lifetime. That is why choosing the right algorithm matters more than buying a faster computer.

Counting steps in real code

def first_item(items):
    return items[0]                  # O(1): the same work for any size

def total(items):
    s = 0
    for x in items:                  # O(n): the loop runs n times
        s += x
    return s

def has_duplicate_slow(items):       # O(n²): compares every pair
    for i in range(len(items)):
        for j in range(i + 1, len(items)):
            if items[i] == items[j]:
                return True
    return False

def has_duplicate_fast(items):       # O(n): a set remembers what we have seen
    seen = set()
    for x in items:
        if x in seen:                # looking in a set is O(1) on average
            return True
        seen.add(x)
    return False

Both duplicate checkers give the same answers, but they scale very differently. Measure it yourself with Python’s timeit:

import timeit

items = list(range(2000))            # no duplicates: the worst case for both
print(timeit.timeit(lambda: has_duplicate_slow(items), number=3))   # slow: about 2 million comparisons per call
print(timeit.timeit(lambda: has_duplicate_fast(items), number=3))   # tiny: 2000 steps per call

Make the list ten times longer and the slow version becomes about a hundred times slower, while the fast one becomes ten times slower. This is the practical meaning of O(n²) versus O(n).

Rules for reading Big O

  1. Drop constants. A loop that runs 3n times is still O(n). Big O describes the shape of the growth, not the exact count.
  2. Keep only the biggest term. n² + n + 7 is O(n²), because for large n the n² part swamps the rest.
  3. Sequential steps add; nested steps multiply. A loop followed by another loop is O(n + n) = O(n). A loop inside a loop is O(n × n) = O(n²).
  4. Halving the problem each step gives O(log n). If you can cut the input in half every time, even a billion items take only about 30 steps.
  5. Different inputs, different letters. Looping over two separate lists of sizes a and b is O(a + b), not O(n).

Best, average and worst case, and memory

The same algorithm can behave differently on different inputs. Searching a list for a value is O(1) if the value is first, but O(n) if it is last or missing. Unless we say otherwise, Big O means the worst case, because that is the guarantee you can plan around. We also measure space complexity: how much extra memory the algorithm uses. has_duplicate_fast is faster than the slow version, but it pays with O(n) extra memory for the set. Many algorithm choices are a trade between time and space.

2. The data structures you need

An algorithm is only as good as the container that holds its data. These are the structures that Python gives you, and what each operation costs. Memorise this table: it explains most performance problems.

Structure Good at Slow at
list (array) Read by index O(1), append at the end O(1) Search x in list O(n), insert or delete at the front or middle O(n)
dict (hash table) Insert, read, delete by key: O(1) on average Keeps no sorted order for range queries
set Membership test x in s, add, remove: O(1) on average No index, no duplicates
collections.deque Add or remove at both ends: O(1) Reading from the middle O(n)
heapq (heap) Get the smallest item O(1), push or pop O(log n) Searching for an arbitrary item O(n)
Sorted list + bisect Find a position in O(log n) Inserting keeps the list sorted but shifts items: O(n)

Two big lessons from the table. First, testing x in some_list inside a loop is a hidden O(n²); turn the list into a set first. Second, never use a list as a queue (list.pop(0) is O(n)); use a deque.

from collections import deque

queue = deque()
queue.append("a")        # join the back of the line
queue.append("b")
first = queue.popleft()  # serve the front: "a", in O(1)

stack = []               # a list is a fine stack: last in, first out
stack.append(1)
stack.append(2)
top = stack.pop()        # 2

Linked structures: trees and graphs

Beyond these built-ins, two ideas appear everywhere. A tree is data arranged as parents and children, like folders on a disk. A graph is a set of points (nodes) joined by connections (edges), like cities and roads or people and friendships. We build both later in this tutorial.

3. Searching

Linear search: O(n)

Look at the items one by one until you find the target. It works on any list, sorted or not, and it is the right choice for short lists you search once.

def linear_search(items, target):
    for index, value in enumerate(items):
        if value == target:
            return index
    return -1                 # not found

Binary search: O(log n)

If the list is sorted, you can do far better. Look at the middle item. If it is the target, you are done. If the target is bigger, it can only be in the right half; if smaller, in the left half. Throw the other half away and repeat. Each step halves the problem, so a list of one billion items needs at most about 30 steps.

def binary_search(items, target):
    low, high = 0, len(items) - 1
    while low <= high:
        mid = (low + high) // 2
        if items[mid] == target:
            return mid
        if items[mid] < target:
            low = mid + 1           # the target is in the right half
        else:
            high = mid - 1          # the target is in the left half
    return -1

numbers = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print(binary_search(numbers, 23))   # 5
print(binary_search(numbers, 7))    # -1

Binary search is easy to describe and famously easy to get wrong. The usual mistakes are low < high instead of <= (missing the last item), and forgetting the + 1 and - 1, which causes an endless loop. In real programs, use Python’s tested version:

from bisect import bisect_left

position = bisect_left(numbers, 23)          # where 23 is, or where it would be inserted
found = position < len(numbers) and numbers[position] == 23
print(position, found)                       # 5 True

The sorted-list requirement has a cost: sorting is O(n log n). If you search only once, linear search is cheaper overall. If you search many times, sort once and use binary search each time, or use a set or dict for O(1) lookups when you only need “is it there?”.

The idea behind it: binary search works whenever you can ask a yes/no question that splits the possibilities cleanly. It is also used to find “the smallest value that works”, for example the lowest server capacity that handles the load.

4. Sorting

Sorting puts items in order. It matters on its own, and it also makes other tasks faster (binary search, finding duplicates, merging). We will build the classic algorithms from slowest to fastest, because the journey teaches the key ideas. In daily work you will almost always call Python’s built-in sorted().

Bubble sort: O(n²)

Walk through the list and swap neighbours that are in the wrong order. After each pass, the largest remaining item has “bubbled” to the end. If a whole pass makes no swap, the list is sorted and we stop early.

def bubble_sort(items):
    items = items[:]                       # work on a copy
    for end in range(len(items) - 1, 0, -1):
        swapped = False
        for i in range(end):
            if items[i] > items[i + 1]:
                items[i], items[i + 1] = items[i + 1], items[i]
                swapped = True
        if not swapped:                    # nothing moved: already sorted
            break
    return items

Selection sort: O(n²)

Find the smallest item and put it first. Then find the smallest of the rest and put it second, and so on. It does few swaps, but always compares all pairs.

def selection_sort(items):
    items = items[:]
    for i in range(len(items) - 1):
        smallest = i
        for j in range(i + 1, len(items)):
            if items[j] < items[smallest]:
                smallest = j
        items[i], items[smallest] = items[smallest], items[i]
    return items

Insertion sort: O(n²), but fast on nearly sorted data

Take items one at a time and slide each into its correct place among the ones already sorted, like arranging playing cards in your hand. On a list that is already almost sorted, it needs only about O(n) steps, which is why real sorting libraries use it for small pieces.

def insertion_sort(items):
    items = items[:]
    for i in range(1, len(items)):
        current = items[i]
        j = i - 1
        while j >= 0 and items[j] > current:
            items[j + 1] = items[j]        # shift larger items to the right
            j -= 1
        items[j + 1] = current
    return items

Merge sort: O(n log n)

This is the first algorithm that is fast and predictable. It uses divide and conquer: split the list in half, sort each half (by calling itself), then merge the two sorted halves into one. Merging two sorted lists is easy and takes O(n): always take the smaller of the two front items.

def merge_sort(items):
    if len(items) <= 1:                    # base case: already sorted
        return items
    mid = len(items) // 2
    left = merge_sort(items[:mid])
    right = merge_sort(items[mid:])
    return merge(left, right)

def merge(left, right):
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:            # <= keeps equal items in their original order (stable)
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])                # one side has leftovers: they are already in order
    result.extend(right[j:])
    return result

Why O(n log n)? The list is halved about log n times, and each level of splitting does O(n) work to merge. The price is O(n) extra memory for the merged lists.

Quick sort: O(n log n) on average

Pick a pivot. Put everything smaller to its left and everything larger to its right, then sort both sides the same way. A random pivot makes the terrible worst case (O(n²)) extremely unlikely. This short version builds new lists, which is easy to read; production versions rearrange the list in place.

import random

def quick_sort(items):
    if len(items) <= 1:
        return items
    pivot = random.choice(items)
    smaller = [x for x in items if x < pivot]
    equal   = [x for x in items if x == pivot]
    larger  = [x for x in items if x > pivot]
    return quick_sort(smaller) + equal + quick_sort(larger)

Heap sort and counting sort

A heap always gives you the smallest item quickly. Push everything in, pop everything out, and you have a sorted list in O(n log n) with no recursion. Counting sort is a different idea: if the values are small whole numbers, just count how many times each appears. It runs in O(n + k), where k is the largest value, and beats every comparison sort when k is small.

import heapq

def heap_sort(items):
    heap = items[:]
    heapq.heapify(heap)                    # arranges the list as a heap in O(n)
    return [heapq.heappop(heap) for _ in range(len(heap))]

def counting_sort(numbers, max_value):
    counts = [0] * (max_value + 1)
    for x in numbers:
        counts[x] += 1
    result = []
    for value, count in enumerate(counts):
        result.extend([value] * count)
    return result

print(counting_sort([4, 1, 3, 4, 0, 1], 4))    # [0, 1, 1, 3, 4, 4]

Comparing the sorting algorithms

Algorithm Typical time Worst case Extra memory Stable?
Bubble sort O(n²) O(n²) O(1) Yes
Selection sort O(n²) O(n²) O(1) No
Insertion sort O(n²), O(n) if nearly sorted O(n²) O(1) Yes
Merge sort O(n log n) O(n log n) O(n) Yes
Quick sort O(n log n) O(n²), very rare with a random pivot O(log n) when done in place No
Heap sort O(n log n) O(n log n) O(1) when done in place No
Counting sort O(n + k) O(n + k) O(k) Yes

A sort is stable if items that compare as equal keep their original order. That matters when you sort by one field, then by another (for example, sort people by name, then by age: people of the same age stay in name order).

What you should actually use

Python’s sorted() and list.sort() use Timsort, a hybrid of merge sort and insertion sort that is stable, O(n log n) in the worst case and close to O(n) on data that is already partly ordered. It is better than anything you will write by hand.

numbers = [5, 2, 9, 1]
print(sorted(numbers))                 # [1, 2, 5, 9]: a new list
numbers.sort(reverse=True)             # sorts in place: [9, 5, 2, 1]

people = [("Ann", 31), ("Bob", 25), ("Cy", 31)]
print(sorted(people, key=lambda p: p[1]))               # by age; Ann stays before Cy (stable)
print(sorted(people, key=lambda p: (-p[1], p[0])))      # oldest first, then by name

The key function tells Python what to compare. Learning to write good keys is more valuable than memorising sorting algorithms.

5. Recursion and backtracking

Recursion means a function that solves a problem by calling itself on a smaller version of the same problem. Every recursive function needs two parts: a base case that stops the recursion with a direct answer, and a recursive case that moves closer to the base case. Forget the base case and the function calls itself until Python raises RecursionError.

def factorial(n):
    if n <= 1:                  # base case
        return 1
    return n * factorial(n - 1)  # smaller problem

print(factorial(5))              # 120 = 5 * 4 * 3 * 2 * 1

Think of each call as a plate stacked on the call stack: factorial(5) waits for factorial(4), which waits for factorial(3), and so on, until the base case returns and the plates unwind. Python allows about 1000 nested calls by default (sys.getrecursionlimit()), so very deep recursion should be turned into a loop.

When recursion goes wrong, and how to fix it

The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8…) are each the sum of the two before. The direct translation is beautiful and terribly slow:

def fib_slow(n):                 # O(2ⁿ): it recomputes the same values again and again
    if n < 2:
        return n
    return fib_slow(n - 1) + fib_slow(n - 2)

fib_slow(35) already takes seconds, because fib(30) is calculated thousands of times. The cure is memoization: remember answers you have already computed.

from functools import lru_cache

@lru_cache(maxsize=None)         # one line adds a cache
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(80))                   # 23416728348467685, instantly: O(n)

This simple idea (remember sub-answers) is the heart of dynamic programming, which we meet in section 10.

Divide and conquer

Merge sort and binary search already used the pattern: split the problem, solve the parts, combine. Here is another classic: raising a number to a power in O(log n) instead of O(n) by squaring.

def power(base, exp):
    if exp == 0:
        return 1
    half = power(base, exp // 2)
    return half * half if exp % 2 == 0 else half * half * base

print(power(2, 30))              # 1073741824, with about 5 multiplications instead of 30

Backtracking: try, check, undo

Backtracking explores all choices step by step and abandons a path as soon as it cannot lead to a solution. It is how you solve puzzles, generate combinations and place pieces on a board. The recipe is: choose, explore, un-choose.

def subsets(items):
    result = []
    def explore(index, current):
        if index == len(items):
            result.append(current[:])      # a copy of the choices made so far
            return
        explore(index + 1, current)        # choice 1: skip this item
        current.append(items[index])       # choice 2: take this item
        explore(index + 1, current)
        current.pop()                      # undo the choice before returning
    explore(0, [])
    return result

print(len(subsets([1, 2, 3])))             # 8 = 2³ subsets

The famous N-Queens puzzle asks how many ways you can put N queens on an N×N chessboard so that no two attack each other. Backtracking places one queen per row and gives up on a row as soon as a column or diagonal is already taken:

def count_n_queens(n):
    cols, diag1, diag2 = set(), set(), set()
    def place(row):
        if row == n:
            return 1                       # all queens placed: one solution
        total = 0
        for col in range(n):
            if col in cols or (row - col) in diag1 or (row + col) in diag2:
                continue                   # attacked: do not even try
            cols.add(col); diag1.add(row - col); diag2.add(row + col)
            total += place(row + 1)
            cols.remove(col); diag1.remove(row - col); diag2.remove(row + col)   # undo
        return total
    return place(0)

print(count_n_queens(6), count_n_queens(8))    # 4 92

Backtracking can still be exponential, but the early “give up” steps prune enormous parts of the search.

6. Everyday patterns: hashing, two pointers, sliding window, prefix sums, stacks

Many real problems fall into a few patterns. Recognising them turns an O(n²) solution into an O(n) one.

Pattern 1: use a dictionary or set to remember

Two Sum: find two numbers in a list that add up to a target. The slow way tries every pair (O(n²)). The fast way remembers the numbers it has seen, and for each new number asks “have I already seen the partner I need?”

def two_sum(numbers, target):
    seen = {}                              # value -> index
    for i, x in enumerate(numbers):
        need = target - x
        if need in seen:
            return seen[need], i
        seen[x] = i
    return None

print(two_sum([2, 7, 11, 15], 9))          # (0, 1)

Counting and grouping are the same idea. collections.Counter counts items; a dictionary of lists groups them. This groups words that are anagrams of each other, using the sorted letters as the key:

from collections import Counter, defaultdict

print(Counter("mississippi").most_common(2))   # [('i', 4), ('s', 4)]

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return list(groups.values())

print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
# [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]

Pattern 2: two pointers

On a sorted list, put one pointer at each end and move them toward each other. If the sum is too small, move the left pointer right; if too big, move the right pointer left. It finds a pair in O(n) with no extra memory.

def pair_with_sum(sorted_numbers, target):
    left, right = 0, len(sorted_numbers) - 1
    while left < right:
        s = sorted_numbers[left] + sorted_numbers[right]
        if s == target:
            return left, right
        if s < target:
            left += 1
        else:
            right -= 1
    return None

print(pair_with_sum([1, 3, 4, 6, 8, 11], 10))   # (2, 3)  because 4 + 6 = 10

Pattern 3: sliding window

To find the best group of k neighbouring items, do not add up each group from scratch. Slide a window along the list: add the new item on the right and remove the one that left on the left.

def max_sum_of_k(numbers, k):
    window = sum(numbers[:k])
    best = window
    for i in range(k, len(numbers)):
        window += numbers[i] - numbers[i - k]    # add the new, remove the old
        best = max(best, window)
    return best

print(max_sum_of_k([2, 1, 5, 1, 3, 2], 3))       # 9  (5 + 1 + 3)

Pattern 4: prefix sums

If you must answer many questions of the form “what is the sum of items from position l to r?”, precompute running totals once. Then any range sum is one subtraction.

from itertools import accumulate

numbers = [3, 1, 4, 1, 5, 9, 2, 6]
prefix = [0] + list(accumulate(numbers))         # prefix[i] = sum of the first i items

def range_sum(l, r):                             # inclusive positions l..r
    return prefix[r + 1] - prefix[l]

print(range_sum(2, 5))                           # 4 + 1 + 5 + 9 = 19

Pattern 5: the stack

A stack is last-in, first-out. It is the right tool whenever the most recent unfinished thing must be handled first: undo buttons, browser history, matching brackets. This checks whether brackets are balanced:

def is_balanced(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in text:
        if ch in "([{":
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack                               # leftovers mean an unclosed bracket

print(is_balanced("{[()]}"), is_balanced("{[(])}"))    # True False

Pattern 6: maximum subarray (Kadane’s algorithm)

Find the contiguous part of a list with the largest sum. At each item, decide: extend the current run, or start fresh here if the run so far is dragging us down. One pass, O(n).

def max_subarray(numbers):
    best = current = numbers[0]
    for x in numbers[1:]:
        current = max(x, current + x)
        best = max(best, current)
    return best

print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))   # 6  (the part 4, -1, 2, 1)

7. Trees

A tree has a root at the top; every item (node) can have children. In a binary tree each node has at most two: left and right. A binary search tree (BST) adds one rule: everything in the left subtree is smaller than the node, everything in the right subtree is larger. That makes searching work like binary search: at each node you discard half of the remaining tree (as long as the tree is reasonably balanced).

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def insert(root, value):
    if root is None:
        return Node(value)
    if value < root.value:
        root.left = insert(root.left, value)
    elif value > root.value:
        root.right = insert(root.right, value)
    return root

def contains(root, value):
    while root:
        if value == root.value:
            return True
        root = root.left if value < root.value else root.right
    return False

root = None
for v in [50, 30, 70, 20, 40, 60, 80]:
    root = insert(root, v)

This builds the tree 50 at the top, 30 and 70 below it, and 20, 40, 60, 80 at the bottom. There are four ways to visit every node, and each has a use:

from collections import deque

def in_order(node):                      # left, node, right: gives sorted order for a BST
    return in_order(node.left) + [node.value] + in_order(node.right) if node else []

def pre_order(node):                     # node, left, right: good for copying a tree
    return [node.value] + pre_order(node.left) + pre_order(node.right) if node else []

def post_order(node):                    # left, right, node: good for deleting a tree
    return post_order(node.left) + post_order(node.right) + [node.value] if node else []

def level_order(node):                   # row by row, using a queue (this is breadth-first search)
    result, queue = [], deque([node] if node else [])
    while queue:
        current = queue.popleft()
        result.append(current.value)
        if current.left:
            queue.append(current.left)
        if current.right:
            queue.append(current.right)
    return result

def height(node):
    return 0 if node is None else 1 + max(height(node.left), height(node.right))

print(in_order(root))      # [20, 30, 40, 50, 60, 70, 80]
print(level_order(root))   # [50, 30, 70, 20, 40, 60, 80]
print(height(root))        # 3
print(contains(root, 60), contains(root, 65))   # True False

A BST is fast only while it stays balanced. If you insert already-sorted values, it degenerates into a long chain and searching becomes O(n). Self-balancing trees (AVL trees, red-black trees) fix this automatically, and databases use a close relative, the B-tree, for their indexes. We explain how that helps queries in SQL Server Indexes Explained.

Heaps and priority queues

A heap is a tree stored in a list where the smallest item is always at the top. It is the structure behind a priority queue: “give me the most urgent item next”. Python’s heapq provides it:

import heapq

tasks = []
heapq.heappush(tasks, (2, "write report"))
heapq.heappush(tasks, (1, "fix outage"))
heapq.heappush(tasks, (3, "lunch"))
print(heapq.heappop(tasks))                 # (1, 'fix outage'): lowest number first

print(heapq.nlargest(3, [5, 1, 9, 3, 7]))   # [9, 7, 5]: the top 3 without sorting everything

8. Graphs: BFS, DFS, topological sort and shortest paths

A graph models connections: roads between cities, links between web pages, dependencies between software packages. The simplest way to store one is an adjacency list: a dictionary that maps each node to the list of its neighbours.

graph = {
    "A": ["B", "C"],
    "B": ["A", "D", "E"],
    "C": ["A", "F"],
    "D": ["B"],
    "E": ["B", "F"],
    "F": ["C", "E"],
}

Every graph search keeps track of visited nodes. Without that, a cycle (A to B to A…) would make the search loop forever.

Breadth-first search (BFS): the shortest path by number of steps

BFS explores the graph in rings: first the start node, then all its neighbours, then their neighbours. It uses a queue. Because it reaches closer nodes first, the first time it finds the goal it has found a path with the fewest edges. That makes it the standard answer to “fewest hops” questions, from social network distance to solving a maze.

from collections import deque

def bfs_shortest_path(graph, start, goal):
    queue = deque([[start]])               # a queue of paths
    visited = {start}
    while queue:
        path = queue.popleft()
        node = path[-1]
        if node == goal:
            return path
        for neighbour in graph[node]:
            if neighbour not in visited:
                visited.add(neighbour)
                queue.append(path + [neighbour])
    return None                            # no route exists

print(bfs_shortest_path(graph, "A", "F"))  # ['A', 'C', 'F']

Time is O(V + E), where V is the number of nodes (vertices) and E the number of edges. For huge graphs, store a “came from” dictionary instead of copying whole paths.

Depth-first search (DFS): go as deep as possible

DFS follows one path to its end, then backs up and tries the next. It uses recursion (or an explicit stack). It is the natural tool to ask “is everything reachable?”, to find connected groups, to detect cycles and to explore all possibilities.

def dfs(graph, node, visited=None):
    if visited is None:
        visited = set()
    visited.add(node)
    for neighbour in graph[node]:
        if neighbour not in visited:
            dfs(graph, neighbour, visited)
    return visited

print(sorted(dfs(graph, "A")))             # ['A', 'B', 'C', 'D', 'E', 'F']

BFS or DFS? Use BFS for the shortest path in an unweighted graph and for anything “level by level”. Use DFS when you need to explore everything, backtrack, or detect cycles. Both are O(V + E).

Topological sort: put tasks in a valid order

When some tasks must come before others (install a library before the program that needs it; build module A before module B), you have a directed acyclic graph. A topological sort lists the tasks so that every dependency comes first. The classic method repeatedly takes a task with no unmet dependencies:

def topological_sort(graph):               # graph[x] = tasks that can only start after x
    indegree = {node: 0 for node in graph}
    for node in graph:
        for nxt in graph[node]:
            indegree[nxt] += 1             # count how many things each task waits for
    queue = deque(n for n, d in indegree.items() if d == 0)
    order = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for nxt in graph[node]:
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                queue.append(nxt)
    return order if len(order) == len(graph) else None   # None means there is a cycle

build = {"compile": ["test", "package"], "test": ["deploy"], "package": ["deploy"], "deploy": []}
print(topological_sort(build))             # ['compile', 'test', 'package', 'deploy']

If a cycle exists (A needs B and B needs A), no valid order exists, and the function returns None. Build tools, package managers and spreadsheets use exactly this.

Dijkstra’s algorithm: shortest path with weights

BFS counts steps. When edges have costs (distance, time, price), you need Dijkstra’s algorithm. It always expands the closest unfinished node, using a priority queue (a heap), and updates the best known distance to its neighbours. It works when no cost is negative.

import heapq

def dijkstra(graph, start):               # graph[node] = [(neighbour, cost), ...]
    dist = {node: float("inf") for node in graph}
    dist[start] = 0
    heap = [(0, start)]
    while heap:
        d, node = heapq.heappop(heap)
        if d > dist[node]:
            continue                       # an outdated entry: a shorter way was already found
        for neighbour, cost in graph[node]:
            new_dist = d + cost
            if new_dist < dist[neighbour]:
                dist[neighbour] = new_dist
                heapq.heappush(heap, (new_dist, neighbour))
    return dist

roads = {
    "A": [("B", 4), ("C", 1)],
    "B": [("D", 1)],
    "C": [("B", 2), ("D", 5)],
    "D": [],
}
print(dijkstra(roads, "A"))               # {'A': 0, 'B': 3, 'C': 1, 'D': 4}

Notice that A to B directly costs 4, but A to C to B costs only 3. The complexity is O((V + E) log V). Routing software, network protocols such as OSPF, and map apps are built on this idea (usually with improvements such as A*).

9. Greedy algorithms

A greedy algorithm builds a solution by always taking the choice that looks best right now, and never reconsidering. When this works, the result is simple and fast. The skill is knowing when it works.

Example that works: scheduling meetings. You have one room and many requests (start, end). To fit the most meetings, always pick the one that ends earliest among those that do not overlap with what you already booked.

def max_meetings(meetings):               # list of (start, end)
    count, last_end = 0, float("-inf")
    for start, end in sorted(meetings, key=lambda m: m[1]):    # earliest finish first
        if start >= last_end:
            count += 1
            last_end = end
    return count

print(max_meetings([(1, 3), (2, 4), (3, 5), (0, 6), (5, 7), (8, 9)]))   # 4

Example that fails: coin change. To pay 6 with coins of 1, 3 and 4, a greedy cashier takes the biggest coin first: 4 + 1 + 1 = three coins. But 3 + 3 uses only two. Greedy gives a wrong answer here:

def greedy_coins(coins, amount):
    count = 0
    for c in sorted(coins, reverse=True):
        count += amount // c
        amount %= c
    return count if amount == 0 else None

print(greedy_coins([1, 3, 4], 6))         # 3   (not the best: 3 + 3 needs only 2)
print(greedy_coins([1, 5, 10, 25], 63))   # 6   (correct for normal money)

Greedy works when the problem has the greedy-choice property: a locally best step can always be part of a globally best answer. Real currencies are designed this way; the coins 1, 3 and 4 are not. When greedy is not guaranteed, you need dynamic programming, our next topic. Other famous greedy algorithms are Huffman coding (compression), Kruskal’s and Prim’s algorithms (the cheapest network that connects all points) and Dijkstra’s algorithm.

10. Dynamic programming

Dynamic programming (DP) solves a problem by breaking it into overlapping smaller problems, solving each small problem once, and storing the answers. You already saw it: fib with lru_cache turned O(2ⁿ) into O(n).

A problem is a DP candidate when (1) it asks for a best/shortest/longest/number of ways, (2) a big answer is built from smaller answers, and (3) the same sub-problems appear again and again. Follow these steps:

  1. Define the state: what does one table entry mean? (“the minimum coins to make amount a“)
  2. Find the recurrence: how does a state come from smaller states?
  3. Set the base case: the smallest answer you know (0 coins make amount 0).
  4. Choose the order: fill the table from small to large (bottom-up), or use recursion with a cache (top-down).

Example 1: minimum coins (fixing the greedy failure)

State: best[a] is the fewest coins that make amount a. For each amount, try every coin c: the answer is one coin plus the best for a - c.

def min_coins(coins, amount):
    INF = float("inf")
    best = [0] + [INF] * amount
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and best[a - c] + 1 < best[a]:
                best[a] = best[a - c] + 1
    return best[amount] if best[amount] != INF else -1

print(min_coins([1, 3, 4], 6))             # 2  (3 + 3), where greedy gave 3
print(min_coins([5, 10], 3))               # -1 (impossible)

It runs in O(amount × number of coins).

Example 2: longest common subsequence

Given two strings, find the length of the longest sequence of characters that appears in both in the same order (not necessarily next to each other). This is how diff tools compare files. State: dp[i][j] is the answer for the first i characters of a and the first j of b. If the last characters match, extend the answer of the smaller problem; otherwise take the better of dropping one character from either string.

def lcs_length(a, b):
    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return dp[-1][-1]

print(lcs_length("ABCBDAB", "BDCABA"))    # 4  (for example "BCBA")

Example 3: the 0/1 knapsack

You have a bag that can carry a limited weight and items with a weight and a value. Each item can be taken once. Which items give the highest total value? Trying all subsets is O(2ⁿ); DP solves it in O(n × capacity). State: dp[c] is the best value using capacity c. The inner loop runs backwards so each item is used only once.

def knapsack(weights, values, capacity):
    dp = [0] * (capacity + 1)
    for w, v in zip(weights, values):
        for c in range(capacity, w - 1, -1):
            dp[c] = max(dp[c], dp[c - w] + v)
    return dp[capacity]

print(knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7))     # 9  (the items of weight 3 and 4)

Example 4: edit distance

How many single-character edits (insert, delete, replace) turn one word into another? Spell checkers and “did you mean” suggestions use it. At each position, compare the three possible last edits and keep the cheapest. This version stores only two rows to save memory.

def edit_distance(a, b):
    prev = list(range(len(b) + 1))
    for i in range(1, len(a) + 1):
        cur = [i] + [0] * len(b)
        for j in range(1, len(b) + 1):
            cost = 0 if a[i - 1] == b[j - 1] else 1
            cur[j] = min(prev[j] + 1,          # delete a character
                         cur[j - 1] + 1,       # insert a character
                         prev[j - 1] + cost)   # replace (or keep if equal)
        prev = cur
    return prev[-1]

print(edit_distance("kitten", "sitting"))      # 3

Greedy or DP? If you can prove the best local choice is always safe, use greedy (faster, simpler). If you cannot, and sub-problems overlap, use DP.

11. Which technique for which problem?

If the problem says… Think about… Typical cost
“Is it in here?” or “have I seen this?” set or dict O(1) per lookup
Find a value in a sorted list; “smallest value that works” Binary search O(log n)
Order things; find duplicates; merge Sort first (sorted), then scan O(n log n)
A pair or triple that adds up to something Dictionary or sort + two pointers O(n) or O(n log n)
Best group of k neighbouring items Sliding window O(n)
Many range-sum questions Prefix sums O(n) once, then O(1)
Matching, nesting, undo Stack O(n)
Fewest steps in a maze or network BFS O(V + E)
Explore everything, find cycles or groups DFS O(V + E)
Cheapest route with costs Dijkstra O((V + E) log V)
Tasks that depend on each other Topological sort O(V + E)
“Most urgent first”; top k items Heap O(log n) per push or pop
All combinations, arrangements, puzzles Backtracking Exponential, with pruning
Best choice always safe (scheduling, compression) Greedy Usually O(n log n)
Best/count/longest, sub-problems repeat Dynamic programming Polynomial

As a rough guide to what is feasible in about one second in Python: O(n²) up to roughly 2,000 to 5,000 items, O(n log n) up to a few hundred thousand, O(n) up to a few million. If your input is bigger than the budget for your algorithm, look for a better algorithm before looking for a faster computer.

12. A practice plan, common mistakes and FAQ

A four-week plan

  1. Week 1: foundations. Big O, lists, dictionaries and sets, linear and binary search. Re-implement binary_search from memory until you can do it without bugs.
  2. Week 2: sorting and recursion. Write insertion sort, merge sort and quick sort without looking. Solve factorial, Fibonacci with memoization, subsets and permutations.
  3. Week 3: patterns and trees. Two Sum, anagrams, sliding window, prefix sums, brackets, a BST with the four traversals.
  4. Week 4: graphs and DP. BFS and DFS on a grid maze, topological sort, Dijkstra, then coin change, LCS and knapsack.

Spend about an hour a day. For each problem: (1) solve it by brute force first, even if slow. (2) Work out its Big O. (3) Ask which pattern from section 11 makes it faster. (4) Test with edge cases: empty input, one item, duplicates, negative numbers, the largest size. Free practice sites with graded problems include LeetCode, HackerRank, Codeforces and Exercism, and the book Grokking Algorithms is a gentle companion.

Common mistakes

  • Optimising before it is correct. Get a working brute-force solution first; use it to test the clever version.
  • Hidden O(n) inside a loop. x in a_list, list.pop(0), list.insert(0, x) and string concatenation in a loop each cost O(n), which makes the whole loop O(n²). Use a set, a deque, or "".join(parts).
  • Off-by-one errors. In binary search, slices and ranges, check the first and last element by hand.
  • Changing a list while looping over it, and forgetting that b = a does not copy a list (use a[:] or a.copy()).
  • No base case in recursion, or recursion that is too deep (turn it into a loop or increase the limit carefully).
  • Forgetting the visited set in graph searches, which causes infinite loops on cycles.
  • Using greedy where DP is needed. Always test greedy against a few small cases you can check by hand.

Quick answers

Do I need advanced maths? No. Basic algebra and the idea of logarithms (“how many times can I halve this?”) are enough for everything in this tutorial.

Which language should I use? Any. The ideas are the same in Python, Java, C#, JavaScript or C. Python is easiest for learning because the code is short. For contests that need speed, people use C++ or Java.

Will I use this in real work? Every day, mostly without noticing. Choosing a dictionary instead of a list, sorting before scanning, avoiding a query inside a loop and understanding why an index makes a database query fast are all algorithmic thinking. The same ideas explain why slow SQL queries are slow, and why a script that handles 100 rows can collapse at 100,000.

Do I need to memorise these algorithms? Not word for word. Understand the idea behind each one (halving, merging, remembering, exploring in rings), know its cost, and be able to rebuild it from that idea. In real code, use the standard library: sorted, bisect, heapq, Counter, deque and lru_cache are tested, fast and already there.

Did you find this helpful?Tap the heart to let us know. It takes one second and no account.

More tutorials like this

Leave a Comment

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

Bigland Network IT

Practical tutorials for people who run, build and fix things: operating systems, databases, development, networking and security.

Topics

More

Site

© 2026 Bigland Network. All rights reserved.Always test commands on a non-production system first.
Scroll to Top