Learn computer science by watching algorithms run
Free interactive lessons on data structures and algorithms. Step through each algorithm on a live visual stage, then practice with problems that check your answers.
Start with Bits, bytes and binary numbers · Browse all 84 topics
Foundations
How computers represent data, how programs run, and how to reason about cost.
Data inside a computer
- Bits, bytes and binary numbers Every number in a computer is a row of bits. Toggle eight bits, watch their place values add up, and convert between decimal and binary…
Analyzing algorithms
- Big-O, Big-Θ and Big-Ω Big-O, Big-Θ and Big-Ω describe how cost grows, ignoring constants. Watch 3n + 5 and n² as n grows and the small terms fade away.
Linear Data Structures
Arrays, strings, linked lists, stacks, queues and hash tables: the building blocks every other structure uses.
Arrays and strings
- Arrays: indexing, traversal, insertion and deletion costs Arrays give instant access by index, but inserting or deleting in the middle shifts every later element. Watch elements shift one by one.
- Dynamic arrays: capacity, growth, amortized append A dynamic array grows by copying into a bigger block when it fills. Doubling the capacity keeps appends O(1) on average.
Linked lists
- Singly linked lists: traverse, insert, delete A singly linked list is a chain of nodes, each pointing to the next. Walk the chain with a cursor and rewire two arrows to insert or delete.
- Linked list techniques: reverse, middle, merge, detect a cycle Four classic list moves: reverse by rewiring pointers, find the middle and detect cycles with slow and fast runners, and merge two sorted…
Stacks and queues
- Stacks: push, pop, peek; array and linked implementations A stack adds and removes at the top only: last in, first out. Watch push, pop and peek on array and linked implementations.
- Queues: enqueue, dequeue; circular buffer A queue adds at the back and removes at the front: first in, first out. A circular buffer reuses its slots as head and tail wrap around.
Hashing
- Hash functions: from key to bucket index A hash function turns a key into a bucket index. See keys map to buckets and how a good function spreads them evenly.
- Hash tables with separate chaining With separate chaining, each bucket holds a small list of the keys that hash there. Insert, search and delete walk one short chain.
- Open addressing: linear, quadratic probing, double hashing Open addressing stores every key in the bucket array itself and probes for the next free slot. Compare linear, quadratic and double-hash…
- Load factor and resizing The load factor is how full a hash table is. When it passes a threshold the table doubles and every key moves to a new bucket.
- Hash sets and maps in practice: counting, lookup, deduplication Hash sets and maps answer "have I seen this?" in O(1). Use them to count, look up, group and deduplicate, as in Two Sum.
- Collisions, worst cases and mutable keys Bad keys can pile into one bucket and turn a hash table into a slow list. Mutable keys can get lost after they change.
Recursion
Functions that call themselves: base cases, the call stack, recursion trees and when to turn recursion into a loop.
Recursion
- Recursion: base case, recursive case, the call stack A recursive function solves a problem by calling itself on a smaller one until it reaches a base case. Watch frames push on each call and…
- Recursion trees: Fibonacci and repeated work Some recursive functions call themselves more than once, forming a tree of calls. Naive Fibonacci repeats the same subtrees again and again.
Searching and Sorting
Finding values quickly and putting data in order, from linear search to merge sort, quick sort and radix sort.
Searching
- Linear search Linear search checks each element from left to right until it finds the target. It works on any array and takes O(n) time.
- Binary search Find a value in a sorted array by looking at the middle and throwing away the half that cannot contain it, until one look remains.
Elementary sorting
- Bubble sort Bubble sort compares neighbours and swaps them when out of order, so the largest values bubble to the end. The sorted suffix grows by one…
- Selection sort Selection sort scans for the smallest remaining value and swaps it into place, one swap per pass. It always takes O(n²) comparisons.
- Insertion sort Insertion sort lifts each element out and slides it left into the sorted prefix. It is fast on nearly sorted data.
Efficient sorting
- Merge sort Merge sort splits the array in half, sorts each half recursively and merges the sorted halves. It always takes O(n log n) time and is…
- Quick sort: partitioning and pivots Quick sort picks a pivot, partitions smaller values left and larger right, then recurses on both sides. It is fast in practice but O(n²)…
- Counting sort Counting sort counts how often each key appears, turns the counts into positions with prefix sums, and places items stably. No comparisons…
Trees and Heaps
Hierarchical structures: binary trees, search trees, heaps, tries and union-find.
Trees
- Trees: root, leaf, depth, height, subtree A tree has a root, children, leaves, depth and height. Hover over a tree to see each term and measure depth with rulers.
- Binary trees and how they are stored In a binary tree each node has at most a left and a right child. See nodes as objects with references, and complete trees stored in an…
- Pre-order, in-order, post-order Pre-order, in-order and post-order visit a tree’s nodes in different orders. Watch visit numbers appear while the call stack grows beside…
- Level-order traversal Level-order traversal visits a tree one level at a time using a queue. Watch the queue fill with each level’s children.
- Recursive problems on trees: height, size, mirror, paths Height, size, mirror images and path sums all follow one pattern: solve both subtrees, then combine at the node. Watch values bubble up to…
- Serialization and construction Serialization turns a tree into a string and back. Watch tokens emitted on the way out and consumed to rebuild the same tree.
Binary search trees
- BST: search, insert, min and max In a binary search tree smaller keys go left and larger keys go right. Each comparison picks a direction, so search and insert follow one…
- BST delete; successor and predecessor Deleting from a BST has three cases: a leaf, one child, or two children replaced by the in-order successor. Find successors by going…
- Validating a BST and the in-order property A tree is a BST only if every node fits the range allowed by all its ancestors. Watch the allowed range shrink down each path.
- Why balance matters Inserting sorted keys turns a BST into a chain with O(n) search. Compare the tree’s height with log n to see why balance matters.
- AVL trees and rotations An AVL tree keeps the heights of every node’s subtrees within one. Single and double rotations restore balance after an insert.
- Red-black trees A red-black tree colours nodes red or black and enforces rules that keep it roughly balanced. Inserts recolor and rotate to fix violations.
- Ordered sets and maps: floor, ceiling, range queries Balanced trees power ordered sets and maps that answer floor, ceiling and range queries. Watch an in-order walk visit only the range.
Heaps and priority queues
- Binary heaps: array layout, sift up, sift down A binary heap is a complete tree stored in an array where every parent is smaller than its children. Sift up after insert and sift down…
- Building a heap in O(n) Heapify builds a heap from an array in O(n) by sifting down from the last internal node backward. Most nodes are near the bottom and move…
- Heap sort Heap sort builds a max-heap, then repeatedly moves the maximum to the end and shrinks the heap. It sorts in place in O(n log n).
- Priority queues in practice: top-k, k-way merge, scheduling Priority queues solve top-k, k-way merge and scheduling problems by always handing you the most urgent item next.
Tries and union-find
- Tries: insert, search, prefix A trie stores words character by character along edges, with markers where words end. Insert, search and prefix queries take time…
- Trie applications: autocomplete, word search, XOR maximum Tries power autocomplete, word search on a grid, word replacement and the maximum XOR of two numbers.
- Disjoint set union: find, union, rank, path compression Union-find tracks which items are in the same group. Parent arrows point toward a root, and path compression flattens them for…
- Union-find applications: connectivity, grouping, redundant edges Add edges one by one and union-find merges components, revealing connectivity, groups and the edge that creates a cycle.
Graphs
Vertices and edges: traversal, shortest paths, spanning trees, connectivity and network flow.
Basics
- Graphs: vertices, edges, directed, weighted, degree, paths A graph is a set of vertices joined by edges, which can be directed or weighted. Learn degree, paths and cycles by hovering over a graph.
- Adjacency matrix, adjacency list, edge list Store a graph as an adjacency matrix, an adjacency list or an edge list. Click an edge to see it in all three and compare their costs.
- Implicit graphs: grids, states and puzzles Many problems are graphs in disguise: grid cells, game states and puzzle positions. Each cell or state is a vertex and each move is an edge.
Traversal
- Breadth-first search Breadth-first search explores a graph in rings of increasing distance using a queue. Watch the frontier expand level by level.
- Depth-first search Depth-first search follows one path as deep as it can, then backtracks. Watch the path dive and retreat alongside the call stack.
- Connected components and flood fill A connected component is a group of vertices that can reach each other. Flood fill colours each component, as in counting islands on a grid.
- Cycle detection in undirected and directed graphs Detect cycles in undirected and directed graphs. In a directed graph, DFS colours nodes white, gray and black, and a gray-to-gray edge…
- Bipartite check by 2-coloring A graph is bipartite when its vertices split into two groups with every edge crossing between them. Two-colour it with BFS and watch for a…
- Topological sort: Kahn's algorithm and DFS finishing order A topological order lists tasks so every dependency comes first. Kahn’s algorithm ticks in-degree counters down; DFS uses finishing order.
Shortest paths
- Shortest paths in unweighted graphs; path reconstruction In an unweighted graph BFS finds shortest paths. Distance labels spread outward and parent arrows trace each path back to the source.
- Dijkstra's algorithm Dijkstra’s algorithm finds shortest paths with non-negative weights. It settles the closest unsettled vertex and relaxes its edges using a…
- Bellman-Ford and negative edges Bellman-Ford relaxes every edge n − 1 times, so it handles negative weights. One more round that still improves a distance reveals a…
- 0-1 BFS and multi-source BFS When edge weights are only 0 or 1, a deque replaces the priority queue. Multi-source BFS starts from many sources at once, as in rotting…
- Floyd-Warshall: all pairs Floyd-Warshall finds shortest paths between every pair of vertices. The distance matrix updates once for each vertex allowed as a midpoint.
- A* search with heuristics A* adds a heuristic estimate of the remaining distance to Dijkstra’s cost. A good heuristic aims the search at the goal and expands fewer…
Spanning trees and connectivity
- Kruskal's algorithm Kruskal’s algorithm builds a minimum spanning tree by taking edges from cheapest to most expensive, skipping any edge that would form a…
- Prim's algorithm Prim’s algorithm grows a minimum spanning tree from one vertex, always adding the cheapest edge that reaches a new vertex.
- Strongly connected components: Kosaraju and Tarjan In a directed graph a strongly connected component is a set where every vertex reaches every other. Find them with Kosaraju’s or Tarjan’s…
Flow and matching
- Maximum flow: Ford-Fulkerson and Edmonds-Karp Maximum flow pushes as much as possible from source to sink without exceeding edge capacities. Augmenting paths push flow and residual…
Problem-Solving Techniques
Reusable ways to attack a problem: two pointers, sliding windows, backtracking, greedy choices and divide and conquer.
Array and pointer patterns
- Hash maps for lookup and counting A hash map remembers what you have already seen, so a single scan can find duplicates, pairs and running counts.
Dynamic Programming
Solve each subproblem once and reuse the answer: memoization, tables, knapsack, string DP and more.
Dynamic Programming
- Overlapping subproblems and memoization Memoization stores each subproblem’s answer the first time it is computed. Repeated subtrees of the recursion tree collapse into cache hits.
- Tabulation: filling the table bottom-up Tabulation fills a table from the smallest subproblems up, so every value it needs is already there. Watch the table fill left to right.
- The DP recipe: state, transition, base cases, order, answer Every DP answers five questions: the state, the transition, the base cases, the fill order and where the answer lives.
- 1-D DP: house robber, decode ways, jump game II One-dimensional DP keeps one value per position, built from the previous one or two, as in house robber and decode ways.
- Kadane's algorithm and maximum subarray Kadane’s algorithm finds the maximum subarray in one pass by tracking the best sum ending here and the best seen so far.
- 0/1 and unbounded knapsack Knapsack picks items to maximise value within a weight limit. A table row per item records whether taking or skipping each item is better.
- Coin change: minimum coins and number of ways Coin change finds the fewest coins for an amount, or the number of ways to make it. Each coin sweeps across the amounts table.
- Longest increasing subsequence; the n log n version The longest increasing subsequence has an O(n²) table solution and an O(n log n) version that keeps a tails array and binary searches it.
- Grid DP: paths, minimum path sum, obstacles Grid DP computes each cell from the cells above and to the left, counting paths or finding the cheapest path around obstacles.
- String DP: LCS, edit distance, palindromic subsequence Two-string DP puts one string on each axis of a table. Longest common subsequence and edit distance fill it cell by cell, moving…
- Space optimization: rolling rows and variables Most DP tables only need the last row or two. Rolling arrays shrink a grid to two rows, then to one, without changing the answer.
- Interval DP: matrix chain, burst balloons, palindrome partitioning Interval DP solves every subrange, shortest first, combining smaller ranges, as in matrix chain order and burst balloons.
- State machine DP: stock problems State machine DP tracks which state you are in on each day, such as holding, sold or cooling down, to solve stock trading problems.
- Bitmask DP: TSP and assignments Bitmask DP uses the bits of an integer to record which items are used, solving the travelling salesperson and assignment problems for…
- Tree DP Tree DP computes answers for each subtree from its children’s answers, as in house robber on a tree and placing cameras.
- Recognizing DP and choosing the state Spot when a problem needs DP: optimal or counting answers built from overlapping choices. Then pick a state that captures what matters.
Advanced Data Structures
Specialised structures for fast queries: caches, segment trees, Fenwick trees, Bloom filters and B-trees.
Advanced Data Structures
- LRU and LFU caches An LRU cache evicts the least recently used item. A hash map plus a doubly linked list gives O(1) get and put. LFU evicts the least…
Computer Systems
How hardware and the operating system run programs: CPUs, caches, processes, scheduling, locks and memory.
Operating systems
- CPU scheduling: FCFS, SJF, priority, round robin The scheduler decides which process runs next: first come first served, shortest job first, priority or round robin. Compare them on a…
Languages, Compilers and Theory of Computation
How code becomes a running program, and what computers can and cannot compute.
Theory of computation
- Finite automata: DFA and NFA A finite automaton reads input one symbol at a time and moves between states, accepting or rejecting. NFAs can always be turned into DFAs.