← Back to Home

⚙️ Algorithms, Visually

The core algorithms behind search boxes, databases, maps and compilers. Watch each one run step by step, count the work it does, and learn which one to choose for which problem.

1. What Is an Algorithm?

An algorithm is a precise, finite sequence of steps that turns an input into an output. A recipe is an algorithm for food. A sorting routine is an algorithm for turning a messy list into an ordered one.

We judge an algorithm on two things:

# find_max.py: a tiny algorithm, with its invariant spelled out
def find_max(items):
    if not items:
        raise ValueError("empty list has no maximum")
    best = items[0]
    for x in items[1:]:        # invariant: best = max of everything seen so far
        if x > best:
            best = x
    return best                # one pass, so O(n) time and O(1) extra memory

print(find_max([7, 2, 9, 4]))  # 9
💡 Think in invariants: a loop invariant is a fact that stays true on every iteration. Here it is "best is the largest value seen so far". If it holds at the start, holds after each step, and you've seen every item, the answer is correct. That habit catches most off-by-one bugs.

2. Measuring Cost with Big-O

Big-O notation describes how an algorithm's work grows with input size n, ignoring constant factors. It answers: "if my data grows 1000×, how much slower does this get?"

Big-ONameExamplen = 1,000,000 means about
O(1)ConstantArray index, hash table lookup1 step
O(log n)LogarithmicBinary search, B-tree lookup20 steps
O(n)LinearScan a list, find max1 million steps
O(n log n)LinearithmicMerge sort, heap sort20 million steps
O(n²)QuadraticBubble sort, compare all pairs1 trillion steps
O(2ⁿ)ExponentialTry every subsetmore steps than atoms in the universe

We usually quote the worst case, because it's a guarantee. Sometimes the average case matters more: quicksort's worst case is O(n²), but on random data it averages O(n log n) and is often the fastest sort in practice.

🔗 Go deeper: the P vs NP tutorial has an interactive growth chart and explains why some problems seem to have no efficient algorithm at all.

4. Sorting: Five Algorithms Side by Side

Sorting is the most studied problem in computer science, because so much else depends on it: binary search, removing duplicates, merging datasets, database indexes. Pick an algorithm and watch it work. Yellow bars are being compared, red bars are being written, and green bars are in their final position.

📊 Sorting visualizer

Comparisons: 0 Writes: 0

AlgorithmBestAverageWorstExtra memoryStable?
Bubble sortnn²n²1Yes
Insertion sortnn²n²1Yes
Selection sortn²n²n²1No
Merge sortn log nn log nn log nnYes
Quicksortn log nn log nn²log nNo
Timsort (Python, Java objects)nn log nn log nnYes

Stable means equal items keep their original order. That matters when you sort by one key after another, for example sorting orders by date and then by customer, so each customer's orders stay in date order.

💡 Try this: run insertion sort on a nearly sorted input and compare the counters with merge sort. Insertion sort does almost no work when items are close to their final position. That is why real-world sorts like Timsort and introsort switch to insertion sort for small or nearly sorted chunks.

5. Recursion and Divide & Conquer

A recursive function solves a problem by calling itself on smaller versions of the same problem, until it reaches a base case small enough to answer directly.

Divide and conquer is the most useful recursive pattern. It has three steps:

  1. Divide the problem into smaller pieces.
  2. Conquer each piece recursively.
  3. Combine the answers.
38 27 43 3 9 82 10
divide ↓
38 27 433 9 82 10
3827 433 982 10
merge ↑ (combine two sorted halves in one pass)
27 38 433 9 10 82
3 9 10 27 38 43 82

Merge sort halves the list log n times, and each level of merging touches all n items. That gives O(n log n).

# merge_sort.py: divide and conquer, O(n log n), stable
def merge_sort(items):
    if len(items) <= 1:                 # base case
        return items
    mid = len(items) // 2
    left = merge_sort(items[:mid])      # conquer each half
    right = merge_sort(items[mid:])
    return merge(left, right)           # combine

def merge(left, right):
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:         # <= keeps equal items in order (stable)
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    out.extend(left[i:])
    out.extend(right[j:])
    return out

print(merge_sort([38, 27, 43, 3, 9, 82, 10]))   # [3, 9, 10, 27, 38, 43, 82]

Other divide-and-conquer algorithms you use without noticing include binary search, quicksort, Karatsuba multiplication (used for big-number arithmetic in cryptography), and the Fast Fourier Transform (used in audio, image compression and 5G radio).

⚠️ Recursion depth: every recursive call uses stack memory. Python's default limit is about 1,000 frames, so a recursive function that shrinks its input by just 1 each call will crash on large inputs. Halving recursions like merge sort only go about 30 levels deep for a billion items, so they're safe.

6. Hash Tables: Lookup in O(1)

A hash table (Python dict, Go map, Java HashMap) stores key–value pairs in an array of buckets. A hash function turns each key into a number, and hash(key) mod buckets picks the bucket. Finding a key means computing its hash and looking in one bucket. You don't scan the whole table.

🗂️ Hash table with chaining

Type a key to see its hash.
Items: 0 Buckets: 8 Load factor: 0.00

When the load factor (items ÷ buckets) passes 0.75, the table doubles its bucket count and re-inserts everything. That keeps chains short, so lookups stay O(1) on average.

When two keys land in the same bucket, that's a collision. This demo handles collisions by chaining, where each bucket holds a small list. Python's dict uses a different technique called open addressing, which probes other slots in the same array. Either way, a good hash function and resizing keep collisions rare.

# Turning an O(n²) problem into O(n) with a hash set
def has_duplicate_slow(items):          # O(n²): compare every pair
    return any(items[i] == items[j]
               for i in range(len(items))
               for j in range(i + 1, len(items)))

def has_duplicate_fast(items):          # O(n): one pass with a set
    seen = set()
    for x in items:
        if x in seen:                   # O(1) average lookup
            return True
        seen.add(x)
    return False

print(has_duplicate_fast([3, 1, 4, 1, 5]))   # True
💡 The most common interview speedup: when you write a nested loop that searches for something, ask whether a set or dict could remember what you've already seen. That one change often turns O(n²) into O(n).

7. Graphs: BFS, DFS, Dijkstra and A*

A graph is a set of nodes connected by edges. Road maps, social networks, web links, package dependencies and network routers are all graphs. The grid below is a graph too: each cell is a node, connected to its four neighbors.

🗺️ Pathfinding: 🟢 start to 🔴 goal

Click or drag on the grid to draw:
Cells explored: 0 Path length: – Path cost: –

AlgorithmExplores usingShortest path?CostUsed for
BFSQueue (FIFO), ring by ringYes, if every edge costs the sameO(V + E)"Degrees of separation", web crawlers, unweighted routing
DFSStack (LIFO), dives deep firstNoO(V + E)Maze generation, cycle detection, topological sort (build order)
DijkstraPriority queue, cheapest firstYes, with non-negative weightsO((V + E) log V)Network routing (OSPF), maps
A*Priority queue on cost + heuristic estimate to goalYes, if the heuristic never overestimatesUsually much less than DijkstraGames, robotics, navigation
# dijkstra.py: shortest paths with non-negative edge weights
import heapq

def dijkstra(graph, source):
    """graph: {node: [(neighbor, weight), ...]}"""
    dist = {source: 0}
    heap = [(0, source)]                 # (distance so far, node)
    while heap:
        d, node = heapq.heappop(heap)    # always expand the cheapest known node
        if d > dist.get(node, float("inf")):
            continue                     # stale heap entry, skip it
        for nbr, w in graph[node]:
            nd = d + w
            if nd < dist.get(nbr, float("inf")):
                dist[nbr] = nd
                heapq.heappush(heap, (nd, nbr))
    return dist

roads = {
    "Home":   [("Cafe", 4), ("Park", 1)],
    "Park":   [("Cafe", 2), ("Office", 6)],
    "Cafe":   [("Office", 1)],
    "Office": [],
}
print(dijkstra(roads, "Home"))
# {'Home': 0, 'Cafe': 3, 'Park': 1, 'Office': 4}   Home → Park → Cafe → Office
💡 Try this: paint a band of mud across the direct route, then run BFS and Dijkstra. BFS counts steps and walks straight through the mud. Dijkstra counts cost and goes around it. Then try A* and compare how many cells each one explores.

8. Greedy vs Dynamic Programming

A greedy algorithm makes the choice that looks best right now and never reconsiders. It's fast and simple, but it's only correct for some problems. Dynamic programming (DP) breaks a problem into overlapping subproblems, solves each one once, and stores the answers, so it can consider every option without repeating work.

The coin change problem

What is the fewest number of coins that adds up to an amount? The greedy approach takes the biggest coin that fits, again and again. Whether that works depends on the coin system.

🪙 Greedy vs DP coin change

🏃 Greedy

–

🧮 Dynamic programming

–

DP table: best[a] = fewest coins to make amount a
# coin_change.py: greedy can fail, DP is always optimal
def greedy(coins, amount):
    used = []
    for c in sorted(coins, reverse=True):
        while amount >= c:
            amount -= c
            used.append(c)
    return used if amount == 0 else None

def min_coins(coins, amount):
    INF = float("inf")
    best = [0] + [INF] * amount          # best[a] = fewest coins for amount a
    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(greedy([1, 3, 4], 6))      # [4, 1, 1]  3 coins
print(min_coins([1, 3, 4], 6))   # 2          (3 + 3)

Why storing answers matters: Fibonacci

The naive recursive Fibonacci recomputes the same values again and again. Adding a cache (memoization) turns exponential time into linear time.

🐇 Function calls to compute fib(n)

Naive recursion
With memoization

# fib.py: one decorator turns O(2^n) into O(n)
from functools import cache

def fib_naive(n):
    return n if n < 2 else fib_naive(n - 1) + fib_naive(n - 2)

@cache                                   # remembers every result it has computed
def fib_memo(n):
    return n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)

print(fib_memo(90))    # 2880067194370816120, instant
# fib_naive(90) would need about 10^19 calls
💡 When to reach for DP: look for two signs. Optimal substructure means the best answer is built from best answers to smaller problems. Overlapping subproblems means the same smaller problems come up repeatedly. Classic examples are edit distance (spell checkers, diff), longest common subsequence (Git merges), the knapsack problem, and route planning.

9. Choosing the Right Algorithm

In day-to-day engineering you rarely write these from scratch. Standard libraries already have tuned versions. What matters is knowing which one fits the problem and what it costs:

If you need to…Reach forCost
Check "have I seen this before?"Hash set / hash mapO(1) average
Look things up in sorted order, or by rangeSorted array + binary search, or a B-tree (database index)O(log n)
Sort recordsThe language's built-in sort (Timsort, pdqsort, introsort)O(n log n)
Always get the smallest or largest item nextHeap / priority queueO(log n) per operation
Find the fewest hops in a networkBFSO(V + E)
Find the cheapest route with weightsDijkstra, or A* if you have a good heuristicO((V + E) log V)
Order tasks that depend on each otherTopological sort (DFS-based)O(V + E)
Find the optimal answer over overlapping choicesDynamic programmingnumber of subproblems × work per subproblem
Get a "good enough" answer to an NP-hard problemGreedy heuristics, approximation algorithms, SAT/ILP solversvaries

Where these run in the real world

🗄️
Databases

B-tree indexes do binary search on disk pages; hash joins use hash tables

🧭
Maps & routing

Dijkstra and A* variants with precomputed shortcuts

🌐
Internet routers

OSPF runs Dijkstra on the network map

🔀
Git diff

Myers' diff algorithm, a shortest-path search over edits

📦
Build tools

Topological sort decides what to compile first

🗜️
Compression

Huffman coding (greedy) inside ZIP, PNG and gzip

⚠️ Measure before optimizing: Big-O ignores constants, caches and memory layout. On small inputs (often under about 50 items) a "worse" O(n²) algorithm can beat an O(n log n) one. Pick the right complexity class first, then profile real workloads.

10. Quiz: Pick the Algorithm

For each scenario, choose the best fit. Click an answer to see the explanation.

🧠 What to remember: first work out the shape of the problem: lookup, ordering, connections, or optimization. Then pick the structure that matches it: hash tables for lookup, sorting and binary search for order, graph search for connections, and dynamic programming or greedy for optimization. Check the cost in Big-O before you write code.
Copied to clipboard!