Algorithms

Searching, graph algorithms and the problem-solving techniques behind them, with step-through visualizations and TypeScript code.

Searching

Find what you need without looking at everything.

Binary search

Find a value in a sorted array by repeatedly halving the range that could contain it: at most about 20 comparisons for a million items.

Sliding window

Keep a contiguous range that grows on the right and shrinks on the left, updating a running result as it moves, to solve substring and subarray problems in O(n).

Two pointers

Walk two indexes through an array, often from both ends towards the middle, to solve pair and partition problems in one O(n) pass instead of O(n²).

Graph algorithms

Traverse, order and find paths through connected data.

Breadth-first search

Explore a graph level by level from a start vertex using a queue, finding the shortest path in number of edges to everything reachable.

Depth-first search

Explore a graph by going as deep as possible along each path before backtracking: the basis of cycle detection, topological sort and maze solving.

Dijkstra's shortest path

Find the cheapest path from one vertex to all others in a graph with non-negative edge weights, by always settling the closest unfinished vertex next.

Minimum spanning tree

Connect every vertex of a weighted graph using the cheapest possible set of edges, with no cycles: Kruskal's and Prim's greedy algorithms.

Topological sort

Order the vertices of a directed acyclic graph so every edge points forward: the order to run tasks, build packages or apply migrations so dependencies come first.

Techniques

General strategies for designing algorithms.

Divide and conquer

Split a problem into independent smaller parts, solve each recursively, and combine the answers: the idea behind merge sort, quicksort and binary search.

Dynamic programming

Solve problems with overlapping subproblems by computing each one once and reusing the answer, often by filling a table: edit distance, knapsack, routing.

Greedy algorithms

Build a solution by always taking the choice that looks best right now, never reconsidering: fast and simple, and optimal only for problems with the right structure.

Recursion & backtracking

Solve a problem by solving smaller versions of itself; backtracking builds solutions one choice at a time and undoes choices that lead to dead ends.