Skip to content

Data Structures & Algorithms

Understand, implement and apply the classic toolkit.

A full, language-neutral course in data structures and algorithms with Python examples. Every topic pairs theory and complexity analysis with your own implementation and a set of problems, from arrays and hashing through trees, graphs and dynamic programming to segment trees, ending with a personal algorithms library and timed problem sets.

01Complexity analysis & math basics

The language for comparing algorithms, plus the math it rests on.

  1. Big-O, Big-Omega & Big-ThetaAsymptotic notation describes how an algorithm's cost grows as the input size n grows, ignoring machine speed and constant factors. Big-O gives an upper bound, Big-Omega a lower bound and Big-Theta a tight bound. It lets you compare algorithms before writing a single benchmark.10 min
  2. Analysing loops & recursive codeYou can usually read an algorithm's complexity straight from its structure. Sequential blocks add, nested loops multiply, and a loop that halves its range runs log n times. Recursive functions are analysed by writing a recurrence and solving it, often with the master theorem.9 min
  3. Amortised analysis & space complexityAmortised analysis averages the cost of an operation over a long sequence, so rare expensive steps are paid for by many cheap ones. Space complexity counts the extra memory an algorithm needs beyond its input, including the recursion stack. Both matter when choosing between otherwise similar solutions.9 min
  4. Math for algorithms: logs, sums, modular arithmeticA small amount of math explains most algorithm costs. Logarithms count halvings, arithmetic and geometric series sum loop work, and modular arithmetic keeps huge numbers manageable. Counting formulas tell you how big a search space is before you try to brute force it.10 min
  5. Python built-ins and their costsPython's built-in containers are already well-tuned data structures, but each operation has a cost you must know. Lists are dynamic arrays, dicts and sets are hash tables, deque is a double-ended queue, and heapq and bisect add heaps and binary search over lists. Choosing the wrong one silently turns O(n) into O(n^2).9 min

02Arrays & strings

Contiguous memory, resizing and the most common interview data type.

  1. Static arrays & memory layoutAn array stores elements of the same size in one contiguous block of memory. The address of element i is the base address plus i times the element size, so indexing is O(1). Inserting or deleting in the middle requires shifting everything after it, which is O(n).10 min
  2. Dynamic arrays & resizingA dynamic array wraps a fixed-size array and tracks size and capacity separately. When it fills up it allocates a bigger array, usually about double, and copies the items across. Python's list works this way, which is why append is amortised O(1).9 min
  3. Strings, immutability & character countingStrings are sequences of characters, and in Python they are immutable, so every modification builds a new string. Many string problems reduce to counting characters, comparing two ends, or scanning once while tracking state. Knowing these patterns solves most palindrome, anagram and parsing questions.9 min
  4. Prefix sums & in-place array techniquesA prefix sum array stores the running total up to each index, so any range sum becomes one subtraction. Building it costs O(n) once, after which each query is O(1). The same idea extends to 2D grids and pairs well with in-place techniques like reversal and partitioning.9 min

03Linked lists, stacks, queues & deques

Pointer-based sequences and the LIFO/FIFO structures built on them.

  1. Singly linked listsA singly linked list is a chain of nodes where each node holds a value and a pointer to the next node. Inserting or removing at the head is O(1), but reaching index i takes O(i) steps. Most linked list problems are careful pointer rewiring, made simpler with a dummy head node.12 min
  2. Doubly linked & circular listsA doubly linked list gives each node both next and prev pointers, so a node can be removed in O(1) when you already hold a reference to it. Circular lists link the tail back to the head. Fast and slow pointer techniques find midpoints and detect cycles without extra memory.11 min
  3. Stacks & expression problemsA stack is last-in, first-out: you push onto the top and pop from the top. It models nested structure, such as brackets, function calls and undo history. Any recursive algorithm can be rewritten with an explicit stack.10 min
  4. Queues, circular buffers & dequesA queue is first-in, first-out: enqueue at the back, dequeue at the front. A circular buffer implements it on a fixed array by wrapping indexes with modulo. A deque allows O(1) pushes and pops at both ends, which powers BFS and sliding window maximum.10 min
  5. Monotonic stacksA monotonic stack keeps its elements in increasing or decreasing order by popping anything that would break the order before pushing. Each element is pushed and popped at most once, so the whole scan is O(n). It answers next-greater, previous-smaller and histogram questions that look quadratic.12 min

04Hashing

Constant-time lookup and the collisions that make it interesting.

  1. Hash functionsA hash function turns a key into an integer that is then reduced to a bucket index. A good one is deterministic, fast and spreads keys uniformly so few keys share a bucket. Keys must not change after insertion, otherwise their hash changes and they can no longer be found.12 min
  2. Hash tables: chaining, open addressing & resizingA hash table stores key-value pairs in an array of buckets chosen by the key's hash. Collisions are handled either by chaining, where each bucket holds a small list, or by open addressing, where you probe for the next free slot. Keeping the load factor low through resizing keeps operations O(1) on average.13 min
  3. Problem patterns with maps & setsMany brute-force solutions compare every pair or rescan the input repeatedly. A hash map remembers what you have already seen, so each new element can be checked in O(1). Two-sum, grouping, frequency counting and prefix-sum counting all follow this idea.11 min

05Recursion, sorting & searching

Think recursively, divide and conquer, then sort and search efficiently.

  1. Recursion & the call stackA recursive function solves a problem by calling itself on a smaller version until it reaches a base case it can answer directly. Each call gets its own frame on the call stack, which unwinds as calls return. Drawing the recursion tree shows both the result and the cost.11 min
  2. Divide and conquerDivide and conquer splits a problem into independent subproblems, solves each recursively and combines the results. Merge sort, quicksort, binary search and fast multiplication all follow this pattern. The cost is captured by a recurrence like T(n) = 2T(n/2) + O(n).12 min
  3. Elementary sorts: bubble, selection, insertionBubble, selection and insertion sort are simple O(n^2) algorithms that sort in place. They are rarely used on large data, but insertion sort is very fast on small or nearly sorted arrays and is used inside hybrid sorts like Timsort. They also introduce stability and in-place sorting.10 min
  4. Merge sortMerge sort splits the array in half, sorts each half recursively and merges the two sorted halves in linear time. It always runs in O(n log n) and is stable, but the standard version needs O(n) extra memory. It is the go-to choice for linked lists and external sorting.11 min
  5. Quicksort & quickselectQuicksort picks a pivot, partitions the array into elements smaller and larger than it, then recursively sorts each side. It sorts in place and is very fast in practice, averaging O(n log n). A poor pivot on sorted input gives O(n^2), so pivots are chosen randomly or by median-of-three.13 min
  6. Counting sort, radix sort & sorting in practiceComparison sorts cannot beat O(n log n), but sorts that use the values themselves can. Counting sort tallies each value in a range of size k for O(n + k) time, and radix sort applies a stable counting sort digit by digit. In everyday Python you use sorted with a key function, which runs Timsort.11 min
  7. Binary search & search on the answerBinary search finds a target in a sorted array by repeatedly halving the search range, in O(log n) time. The same idea works on any monotonic yes-or-no condition, such as the smallest speed that finishes a job in time. Clear invariants about what lo and hi mean prevent off-by-one bugs.13 min

06Trees, heaps & tries

Hierarchical structures for ordered data, priorities and prefixes.

  1. Binary trees & traversalsA binary tree is a hierarchy where each node has at most two children. Depth-first traversals visit nodes in pre-order, in-order or post-order, and breadth-first traversal visits level by level with a queue. Most tree problems are a traversal plus a little work at each node.11 min
  2. Binary search treesA binary search tree keeps every left descendant smaller and every right descendant larger than the node. Search, insert and delete follow one root-to-leaf path, so they cost O(h). If keys arrive in sorted order the tree degenerates into a linked list and h becomes n.11 min
  3. Balanced trees: AVL & red-black conceptsSelf-balancing trees restructure themselves with rotations after inserts and deletes so height stays O(log n). AVL trees keep subtree heights within one of each other, while red-black trees use colouring rules that allow a little more imbalance in exchange for fewer rotations. They back ordered maps in many standard libraries.12 min
  4. Binary heapsA binary heap is a complete binary tree stored in an array where every parent is no larger than its children (for a min-heap). The minimum is always at index 0. Push adds at the end and sifts up, pop moves the last item to the root and sifts down, each in O(log n).11 min
  5. Priority queues & heap sortA priority queue always hands out the highest-priority item next, and a heap is the standard implementation. In Python you use heapq on a plain list. Heaps power top-k queries, merging sorted streams, running medians, schedulers and Dijkstra's algorithm, and heap sort sorts in place in O(n log n).11 min
  6. Tries (prefix trees)A trie stores strings character by character along paths from the root, so words with a common prefix share nodes. Lookup and insert cost O(L) for a word of length L, independent of how many words are stored. Tries shine for prefix search, autocomplete and word games.10 min

07Graphs: representations & traversal

Model relationships and explore them systematically.

  1. Graph representationsA graph is a set of vertices connected by edges, which may be directed, undirected or weighted. The representation you pick decides the cost of every later algorithm. Adjacency lists suit the sparse graphs common in practice, while adjacency matrices suit dense graphs and constant-time edge checks.13 min
  2. Breadth-first searchBreadth-first search explores a graph in rings: first all neighbours of the start, then their neighbours, and so on. Because it visits vertices in order of distance, BFS finds shortest paths in unweighted graphs. It uses a queue and a visited set.13 min
  3. Depth-first search, components & cyclesDepth-first search follows one path as far as it can before backtracking. It is the basis for counting connected components, detecting cycles, flood fill and topological sorting. It can be written recursively or with an explicit stack.12 min
  4. Topological sortA topological order lists the vertices of a directed acyclic graph so every edge points forward. It answers questions like the order to take courses or build modules. Kahn's algorithm repeatedly removes vertices with no incoming edges; if some remain, the graph has a cycle.12 min
  5. Union-find (disjoint set union)Union-find, or disjoint set union, tracks which elements belong to the same group as groups merge. find returns a group's representative and union merges two groups. With path compression and union by rank, each operation is nearly constant time.12 min

08Shortest paths & minimum spanning trees

Weighted graph algorithms for routes and cheap networks.

  1. Dijkstra's algorithmDijkstra's algorithm finds the shortest distance from a source to every vertex when all edge weights are non-negative. It always expands the closest unfinished vertex, taken from a min-heap, and relaxes its outgoing edges. It is the core of route planning and network routing protocols such as OSPF.12 min
  2. Bellman-Ford & Floyd-WarshallBellman-Ford relaxes every edge V-1 times, which is enough for shortest paths with up to V-1 edges, and it works with negative weights. A further pass that still improves a distance proves a negative cycle. Floyd-Warshall computes shortest paths between all pairs with a triple loop.12 min
  3. Minimum spanning trees: Kruskal & PrimA minimum spanning tree connects every vertex of a weighted undirected graph with the smallest total edge weight and no cycles. Kruskal's algorithm adds the cheapest edges that do not form a cycle, using union-find. Prim's algorithm grows one tree outward by always taking the cheapest edge leaving it.12 min

09Greedy algorithms & dynamic programming

Optimisation by local choice, or by reusing overlapping subproblems.

  1. Greedy algorithmsA greedy algorithm makes the locally best choice at each step and never revisits it. It works only when the problem has the greedy-choice property, which you justify with an exchange argument. When it applies it is usually simple and fast, often a sort followed by one pass.12 min
  2. DP fundamentals: memoisation & 1D tabulationDynamic programming solves problems whose subproblems overlap by computing each subproblem once and reusing it. Top-down DP adds a cache to a recursive solution; bottom-up DP fills a table in dependency order. Define the state, the recurrence, the base cases and the answer location before writing code.11 min
  3. 2D DP: grids & two sequencesTwo-dimensional DP uses states with two indexes, such as a grid cell or a position in each of two strings. Each cell depends on a few neighbours, usually above, left or diagonal, so the table is filled row by row. Edit distance and grid path counting are the classic examples.12 min
  4. Knapsack problemsIn 0/1 knapsack each item can be taken at most once to maximise value within a weight capacity. The state is the best value for each capacity using the items seen so far. Many problems are knapsack in disguise, including subset sum, equal partition and coin change.13 min
  5. LIS & LCSThe longest increasing subsequence and longest common subsequence are two of the most reused DP patterns. LIS has a simple O(n^2) DP and an O(n log n) method that keeps the smallest tail for each length. LCS fills a 2D table comparing prefixes of two sequences.11 min
  6. Interval DPInterval DP defines a state for every contiguous range i to j and builds answers for longer intervals from shorter ones. A typical transition tries every split point k inside the interval. Matrix chain multiplication, burst balloons and palindrome partitioning all use this shape.12 min

10Backtracking & bit manipulation

Systematic search with pruning, and tricks with binary representations.

  1. Backtracking: subsets, permutations, combinationsBacktracking builds candidate solutions one choice at a time and undoes the last choice when it leads nowhere. It systematically explores a tree of decisions, generating subsets, permutations and combinations. The choose, explore, unchoose template fits almost every problem in this family.11 min
  2. Constraint search & pruningConstraint problems like N-Queens, Sudoku and word search are backtracking with strong pruning. Before exploring a choice you check it against the constraints and abandon whole branches that cannot succeed. Good pruning and fast constraint checks make exponential searches practical.13 min
  3. Bit manipulationIntegers are stored in binary, and bitwise operators let you read and change individual bits in O(1). Bit tricks test powers of two, count set bits and find a unique element with XOR. A bitmask can represent a subset of up to about 20 to 30 items, enabling compact DP and enumeration.13 min

11Advanced patterns & range structures

Linear-time array patterns and logarithmic range queries.

  1. Two pointersThe two-pointer pattern moves two indexes through a sequence, either towards each other from both ends or in the same direction at different speeds. On sorted data it replaces an O(n^2) pair search with an O(n) scan. It also powers in-place deduplication and partitioning.13 min
  2. Sliding windowA sliding window maintains a contiguous range of the input and updates its summary as the range moves, instead of recomputing from scratch. Fixed windows slide one step at a time; variable windows grow the right edge and shrink the left edge while a condition is violated. Each element enters and leaves the window once, so the total is O(n).12 min
  3. Fenwick tree (binary indexed tree)A Fenwick tree, or binary indexed tree, stores partial sums in a plain array so both prefix-sum queries and point updates cost O(log n). Each index is responsible for a range whose length is its lowest set bit. It is shorter to code than a segment tree when you only need sums.13 min
  4. Segment treesA segment tree is a binary tree where each node stores an aggregate, such as sum, min or max, for a segment of the array. Queries combine O(log n) nodes and point updates refresh one root-to-leaf path. Lazy propagation extends it to range updates by deferring work to children until needed.14 min

12Capstone: library & timed problem sets

Consolidate everything into your own tested library and timed practice.

  1. Build a tested algorithms libraryBuilding your own algorithms library turns scattered exercises into a single tested codebase you understand completely. Each structure gets an implementation, tests that cover edge cases, a documented complexity and a benchmark against Python's built-ins. It becomes both a portfolio piece and a personal reference.12 min
  2. Timed problem-solving sessionsTimed sessions train you to solve unfamiliar problems under pressure with a repeatable method. Clarify the problem, work examples, pick a pattern, state complexity, code, then test with edge cases. Logging every miss shows which patterns need more practice.12 min
  3. Pattern review & spaced repetitionMost problems are variations of a few dozen patterns. A cheat sheet that maps problem signals to patterns, combined with spaced repetition, keeps every topic fresh and speeds up recognition. Re-solving one representative problem per pattern is the most efficient review.11 min