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.
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
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.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-O | Name | Example | n = 1,000,000 means about |
|---|---|---|---|
O(1) | Constant | Array index, hash table lookup | 1 step |
O(log n) | Logarithmic | Binary search, B-tree lookup | 20 steps |
O(n) | Linear | Scan a list, find max | 1 million steps |
O(n log n) | Linearithmic | Merge sort, heap sort | 20 million steps |
O(n²) | Quadratic | Bubble sort, compare all pairs | 1 trillion steps |
O(2ⁿ) | Exponential | Try every subset | more 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.
Linear search checks items one by one: O(n), but it works on any list. Binary search needs a sorted list. It checks the middle item, then throws away the half that can't contain the target. Each step halves the remaining range, so a sorted list of 1 billion items takes at most 30 steps.
# binary_search.py: O(log n) on a sorted list
def binary_search(items, target):
lo, hi = 0, len(items) - 1
while lo <= hi: # invariant: target, if present, is in items[lo..hi]
mid = (lo + hi) // 2
if items[mid] == target:
return mid
if items[mid] < target:
lo = mid + 1 # discard the left half
else:
hi = mid - 1 # discard the right half
return -1
print(binary_search([2, 5, 8, 12, 16, 23, 38, 56, 72, 91], 23)) # 5
# In real code use the standard library: bisect.bisect_left(items, target)
lo < hi instead of lo <= hi, forgetting the +1/-1 (which loops forever), and running it on unsorted data. Prefer bisect in Python, sort.Search in Go, or Arrays.binarySearch in Java.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.
| Algorithm | Best | Average | Worst | Extra memory | Stable? |
|---|---|---|---|---|---|
| Bubble sort | n | n² | n² | 1 | Yes |
| Insertion sort | n | n² | n² | 1 | Yes |
| Selection sort | n² | n² | n² | 1 | No |
| Merge sort | n log n | n log n | n log n | n | Yes |
| Quicksort | n log n | n log n | n² | log n | No |
| Timsort (Python, Java objects) | n | n log n | n log n | n | Yes |
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.
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:
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).
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.
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
set or dict could remember what you've already seen. That one change often turns O(n²) into O(n).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.
| Algorithm | Explores using | Shortest path? | Cost | Used for |
|---|---|---|---|---|
| BFS | Queue (FIFO), ring by ring | Yes, if every edge costs the same | O(V + E) | "Degrees of separation", web crawlers, unweighted routing |
| DFS | Stack (LIFO), dives deep first | No | O(V + E) | Maze generation, cycle detection, topological sort (build order) |
| Dijkstra | Priority queue, cheapest first | Yes, with non-negative weights | O((V + E) log V) | Network routing (OSPF), maps |
| A* | Priority queue on cost + heuristic estimate to goal | Yes, if the heuristic never overestimates | Usually much less than Dijkstra | Games, 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
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.
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.
# 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)
The naive recursive Fibonacci recomputes the same values again and again. Adding a cache (memoization) turns exponential time into linear time.
# 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
diff), longest common subsequence (Git merges), the knapsack problem, and route planning.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 for | Cost |
|---|---|---|
| Check "have I seen this before?" | Hash set / hash map | O(1) average |
| Look things up in sorted order, or by range | Sorted array + binary search, or a B-tree (database index) | O(log n) |
| Sort records | The language's built-in sort (Timsort, pdqsort, introsort) | O(n log n) |
| Always get the smallest or largest item next | Heap / priority queue | O(log n) per operation |
| Find the fewest hops in a network | BFS | O(V + E) |
| Find the cheapest route with weights | Dijkstra, or A* if you have a good heuristic | O((V + E) log V) |
| Order tasks that depend on each other | Topological sort (DFS-based) | O(V + E) |
| Find the optimal answer over overlapping choices | Dynamic programming | number of subproblems × work per subproblem |
| Get a "good enough" answer to an NP-hard problem | Greedy heuristics, approximation algorithms, SAT/ILP solvers | varies |
B-tree indexes do binary search on disk pages; hash joins use hash tables
Dijkstra and A* variants with precomputed shortcuts
OSPF runs Dijkstra on the network map
Myers' diff algorithm, a shortest-path search over edits
Topological sort decides what to compile first
Huffman coding (greedy) inside ZIP, PNG and gzip
O(n²) algorithm can beat an O(n log n) one. Pick the right complexity class first, then profile real workloads.For each scenario, choose the best fit. Click an answer to see the explanation.