Skip to content
Tutorials Center
My learning

Topics

DSA Tutorial

Learn data structures and algorithms with Python, from Big O and arrays to trees, graphs, dynamic programming and interview problems. 225 lessons with code that runs in your browser.

Start learning →

of lessons completed

Getting Started

  1. 1 Introduction to Data Structures and Algorithms Learn what data structures and algorithms are, why they matter, and how this Python tutorial takes you from arrays and Big O to graphs and dynamic programming.
  2. 2 Python You Need for DSA Python review for DSA: lists, dicts, sets, slicing, comprehensions, classes, recursion, generators, sorted with key, and the traps that bite in interviews.
  3. 3 Memory and Data Layout See how memory is organized, why arrays sit side by side while linked nodes are scattered, how Python references work, and what is vs == really compares.
  4. 4 Abstract Data Types and Data Structures Learn the difference between an abstract data type and its implementation, meet the List, Stack, Queue, Map, Set and Priority Queue, and choose by operations.
  5. 5 How to Solve Algorithm Problems A repeatable method for algorithm problems: understand, work examples, brute force, optimize, code, test. Includes edge cases, asserts, and reading constraints.

Analyzing Algorithms

  1. 6 Big O Notation Understand Big O notation from scratch. Compare growth rates from O(1) to O(n!), learn to drop constants, meet Omega and Theta, and count real operations.
  2. 7 Analyzing Loops and Code Learn to read code and work out its time complexity. Single loops, nested loops, halving loops, dependent loops and the hidden cost of Python built-ins.
  3. 8 Space Complexity Learn how to measure the memory an algorithm uses. Auxiliary space vs input space, recursion stack cost, in-place algorithms and time-space trade-offs in Python.
  4. 9 Best, Worst and Average Case Understand why one algorithm can have several running times. Compare best, worst and average case with linear search, insertion sort and quicksort pivots.
  5. 10 Amortized Analysis Learn amortized analysis with dynamic arrays, binary counters and multipop stacks. Aggregate, accounting and potential methods explained step by step.
  6. 11 Recurrences and the Master Theorem Solve recursive running times step by step. Learn recurrence relations, recursion trees, unrolling and the three cases of the master theorem, with Python demos.
  7. 12 Complexity Cheat Sheet A one-page Big O cheat sheet for data structures, sorting, searching, graph algorithms and Python built-ins, plus how input limits tell you the target complexity.

Arrays and Lists

  1. 13 Arrays and Python Lists Learn how arrays store data in a row, why indexing is O(1) while insert and delete cost O(n), and how Python lists, the array module and 2D lists behave.
  2. 14 Array Operations Master the core array operations in Python: traverse, search, reverse, rotate three ways, merge sorted arrays and remove duplicates in place, with traces and costs.
  3. 15 Dynamic Arrays Build your own resizable array in Python. Learn capacity vs size, why doubling makes append O(1) amortized, when to shrink, and how Python lists over-allocate.
  4. 16 Two Pointers Learn the two pointers technique in Python: opposite ends, same direction and fast/slow pointers, with pair sum, remove elements, container with most water and 3Sum.
  5. 17 Sliding Window Learn the sliding window technique in Python with fixed windows (max sum of k), variable windows (longest substring without repeats), a reusable template and traces.
  6. 18 Prefix Sums and Difference Arrays Answer range sum queries in O(1) with prefix sums, extend to 2D grids, count subarrays with sum k using a dict, and apply range updates with difference arrays.
  7. 19 Subarray Problems and Kadane's Algorithm Solve the maximum subarray and maximum product subarray problems in Python. Go from a brute force to Kadane's O(n) algorithm, and track the indices too.
  8. 20 Partitioning, Dutch Flag and In-place Tricks Learn Lomuto and Hoare partitioning, the Dutch national flag, move zeroes, quickselect and cyclic-sort index tricks to rearrange arrays in place in Python.
  9. 21 Matrices and 2D Arrays Work with 2D arrays in Python: traversal orders, transpose, rotate 90 degrees, spiral order, diagonals, searching a sorted matrix and a grid neighbours helper.
  10. 22 Matrix Classics: Pascal, Magic Squares, Toeplitz, Sudoku and Max-Sum Rectangle Practice 2D array skills in Python with six classic exercises: Pascal's triangle, odd magic squares, Toeplitz check, Sudoku validation, tic-tac-toe and max-sum rectangle.
  11. 23 Next Permutation and Lexicographic Order Learn the next permutation algorithm in Python: find the pivot, swap, reverse the suffix, then generate all permutations in order, rank and unrank them.
  12. 24 Classic Array Problems: Rain Water, Two-Array Median, Rotations Master three classic array interview problems in Python: trapping rain water three ways, the median of two sorted arrays in O(log n) and rotated arrays.

Strings

  1. 25 Strings in DSA Understand how strings behave in algorithms: immutability, the cost of concatenation and slicing, join, Unicode versus ASCII, and counting characters.
  2. 26 Classic String Problems Solve the classic interview string problems in Python: palindromes, anagrams, reverse words, run-length compression, common prefix, brackets and rotations.
  3. 27 String Parsing Problems: atoi, IP Validation, Big Multiplication and Isomorphic Strings Solve implementation-heavy string problems in Python: a safe atoi with overflow clamping, IPv4 and IPv6 validation, multiplying huge numbers as strings and isomorphic strings.
  4. 28 Alien Dictionary and Lexicographic Rank of a String Recover an unknown alphabet order from a sorted word list with topological sort, then compute the lexicographic rank of a string and the k-th permutation, with and without repeated letters.
  5. 29 Pattern Matching: Naive and KMP Search for a pattern in a text. Start with brute force O(nm), then learn the KMP failure table (LPS) and see step-by-step traces and comparison counts.
  6. 30 Rabin-Karp and String Hashing Learn the Rabin-Karp algorithm and polynomial rolling hashes in Python. Search for patterns, handle collisions, match many patterns and compare substrings fast.
  7. 31 The Z-Algorithm Learn the Z-algorithm step by step in Python. Build the Z array in O(n), search patterns in linear time, and solve prefix, border and period problems.
  8. 32 Palindromic Substrings and Manacher Find palindromic substrings in Python. Compare brute force O(n^3), expand around center O(n^2) and Manacher's linear algorithm with traces and complexity.
  9. 33 Suffix Arrays and Suffix Trees Build a suffix array by sorting, speed it up with prefix doubling, compute the LCP array with Kasai, and solve substring problems. Suffix trees explained.
  10. 34 Lyndon Words, Booth's Algorithm and Burrows-Wheeler Transform Learn Lyndon words and Duval's factorization, find the minimal rotation of a string in O(n) and build the Burrows-Wheeler transform and its inverse in Python.
  11. 35 String Compression and Encoding Problems Solve string compression and encoding problems in Python: run-length encoding, the LZ77 idea, Roman numerals and base conversion, with tests.

Linked Lists

  1. 36 Linked Lists Learn what a linked list is: nodes, pointers, head and tail. Build one by hand in Python, compare it with arrays and see when each structure is faster.
  2. 37 Singly Linked List Implement a singly linked list in Python from scratch: append, prepend, insert, delete, find, length and iteration, with traces, complexity and common bugs.
  3. 38 Doubly Linked List Build a doubly linked list in Python: prev and next pointers, sentinel nodes, O(1) deletion of a node you hold, two-way iteration and complexity.
  4. 39 Circular Linked Lists Learn circular linked lists in Python: the tail-pointer trick, safe traversal, circular doubly lists, round-robin scheduling and the Josephus problem.
  5. 40 Linked List Techniques Core linked list techniques in Python: reverse a list, fast and slow pointers, Floyd cycle detection, merging sorted lists, remove nth from end, dummy nodes.
  6. 41 Linked List Problems Solve classic linked list problems in Python, brute force first: palindrome list, intersection, add two numbers, random-pointer copy, reorder and LRU cache.
  7. 42 Unrolled and XOR Linked Lists Two clever linked list variants: unrolled lists store many items per node for cache-friendly speed, XOR lists store one link for two pointers. With code.

Stacks and Queues

  1. 43 Stacks Learn the stack data structure in Python: LIFO order, push, pop and peek, list and linked implementations, the call stack, undo and O(1) complexity.
  2. 44 Stack Applications See what stacks are for: balanced brackets, infix to postfix, evaluating expressions, a min stack with O(1) minimum and browser history, all in Python.
  3. 45 Stack Puzzles: Permutations, Recursive Sort and Reverse, k Stacks in One Array Solve classic stack puzzles in Python: check stack permutations, sort and reverse a stack with recursion only, and share one array between k stacks efficiently.
  4. 46 Monotonic Stack Learn the monotonic stack in Python: next greater element, daily temperatures, stock span and largest rectangle in a histogram, with traces and O(n) analysis.
  5. 47 Queues Understand queues in Python: FIFO order, why list.pop(0) is slow, collections.deque, a linked-list queue, and a queue built from two stacks, with complexity.
  6. 48 Queue Puzzles: Binary Numbers, Snakes and Ladders, Stack from Queues, k Queues Practice queue problems in Python: generate binary numbers 1 to n, find the fewest dice throws in Snakes and Ladders, build a stack from queues and share one array between k queues.
  7. 49 Circular Queue and Ring Buffer Build a circular queue (ring buffer) in Python with a fixed-size array, wrap-around head and tail, full and empty detection, overwriting mode and real uses.
  8. 50 Deques and Monotonic Queues Learn the double-ended queue (deque) in Python and the monotonic queue trick that solves sliding window maximum and minimum in O(n), with traces and code.
  9. 51 Priority Queues Learn priority queues in Python: the concept, unsorted and sorted list versions, a preview of heaps, heapq vs queue.PriorityQueue and a task scheduler example.

Hashing

  1. 52 Hash Tables Learn how hash tables work: hash function, buckets, collisions, load factor and resizing. Build a tiny hash map in Python and see why lookups are O(1) on average.
  2. 53 Collision Handling Learn how hash tables handle collisions in Python: separate chaining, linear and quadratic probing, double hashing, tombstones and resizing, with full implementations.
  3. 54 Hash Functions Learn what makes a good hash function, build integer and string hashes, and understand Python's hash(), hashability, __hash__ and __eq__, and why lists can't be dict keys.
  4. 55 Dictionaries and Sets in Practice Use Python dictionaries and sets like a pro: operation costs, get, setdefault, defaultdict, Counter, set algebra, insertion order and the traps that cause bugs.
  5. 56 Hashing Patterns Solve classic interview problems with hash maps and sets in Python: duplicates, two sum, group anagrams, longest consecutive sequence, subarray sum k, first unique character.
  6. 57 Bloom Filters and Probabilistic Sets Learn how Bloom filters answer set membership in tiny memory: bit arrays, k hash functions, false positives, the sizing formula, a Python implementation and count-min sketch.
  7. 58 Designing an LRU Cache Design an LRU cache with O(1) get and put in Python: dictionary plus doubly linked list, the OrderedDict shortcut, functools.lru_cache, and an O(1) LFU cache.
  8. 59 Consistent Hashing Understand consistent hashing: why hash(key) % n breaks when servers change, how a hash ring moves few keys, and how virtual nodes balance the load.

Recursion and Backtracking

  1. 60 Recursion Learn recursion in Python from scratch: base case, recursive case, the call stack traced step by step, factorial, sum, power, reverse and the RecursionError limit.
  2. 61 Recursion Patterns Learn the main shapes of recursion in Python: linear, binary, tail and mutual recursion, plus how to turn recursion into a loop with an explicit stack.
  3. 62 Divide and Conquer Learn divide and conquer in Python: split, solve and combine. Covers fast power, merge sort, counting inversions, closest pair and Karatsuba with complexity.
  4. 63 Backtracking Learn backtracking in Python: the choose-explore-undo template, the search tree, pruning, and worked examples such as binary strings and generating parentheses.
  5. 64 Subsets, Permutations and Combinations Generate all subsets, permutations and combinations in Python with backtracking, handle duplicates correctly, compare with itertools and learn the counts 2^n, n!, C(n,k).
  6. 65 N-Queens Solve the N-Queens problem in Python with backtracking: constraint checking with sets, diagonal formulas, solution counts for n=1 to 8, board printing and bitmask speed-up.
  7. 66 Sudoku and Constraint Puzzles Solve constraint puzzles with backtracking in Python: a fast Sudoku solver with row, column and box sets, word search in a grid, rat in a maze and the knight's tour.
  8. 67 More Backtracking Classics Practice backtracking in Python with graph m-coloring, tug of war, removing invalid parentheses, cryptarithmetic puzzles and partitioning into k equal subsets.
  9. 68 Meet in the Middle and Branch and Bound Cut exponential searches down with meet in the middle (subset sum in 2^(n/2)) and branch and bound (knapsack and a tiny travelling salesman), with Python code and counts.
  10. 69 Exact Cover and Dancing Links (Algorithm X) Solve exact cover problems with Knuth's Algorithm X and the Dancing Links data structure in Python, then use it to count N-queens solutions and solve Sudoku.
  11. 70 Tower of Hanoi Solve the Tower of Hanoi in Python with recursion, prove it needs 2^n - 1 moves, count moves, and learn the iterative solution and the ruler-sequence pattern.
  12. 71 Josephus Problem Solve the Josephus problem in Python: simulate the circle, derive the O(n) recurrence, and use the one-bit rotation trick for k = 2 in O(1) time.

Searching

  1. 72 Linear Search Learn linear search in Python: the algorithm step by step, early exit, the sentinel trick, searching objects, finding all matches, comparison counts and when it is enough.
  2. 73 Binary Search Learn binary search in Python: the halving idea, an invariant-based loop that avoids off-by-one bugs, the recursive version, the bisect module and step counts up to a million items.
  3. 74 Binary Search Variants Binary search variants in Python: lower and upper bound, rotated array, peak, 2D matrix, nearly sorted, fixed point, unbounded and mountain arrays.
  4. 75 Binary Search on the Answer Learn to binary search on the answer in Python: monotonic yes/no checks, integer square root, Koko eating bananas, split array largest sum, maximising a minimum, and floats.
  5. 76 Jump, Exponential, Interpolation, Ternary and Other Searches Learn searches beyond binary search in Python: jump, exponential, interpolation, ternary, meta binary, Fibonacci and best-first search, with traces and step counts.

Sorting

  1. 77 Sorting Basics Understand sorting before you learn the algorithms: stability, in-place sorting, the n log n lower bound, and how to use sorted, sort, key and cmp_to_key in Python.
  2. 78 Bubble Sort Learn bubble sort in Python with a step-by-step trace, the swapped-flag optimisation, comparison and swap counters, O(nยฒ) complexity and when (not) to use it.
  3. 79 Selection Sort Learn selection sort in Python: find the minimum, swap it into place, repeat. Includes a trace, swap counts, why it is not stable, a stable variant and O(nยฒ) analysis.
  4. 80 Insertion Sort Learn insertion sort in Python with a clear trace, shift counters, why it is fast on nearly sorted data, binary insertion, online sorting with bisect and O(nยฒ) analysis.
  5. 81 Merge Sort Learn merge sort in Python: split, sort and merge, with traces, top-down and bottom-up versions, O(n log n) analysis, stability, extra space and counting inversions.
  6. 82 Quick Sort Learn quick sort in Python. Partition schemes, pivot choices, the O(n^2) worst case, randomization, 3-way partitioning and quickselect, with traces.
  7. 83 Heap Sort Learn heap sort in Python: how a max-heap stored in a list sorts in place in O(n log n), with sift-down traces, build-heap analysis and a quick sort comparison.
  8. 84 Counting, Radix and Bucket Sort Learn non-comparison sorting in Python. Stable counting sort, LSD radix sort and bucket sort beat O(n log n) in the right cases, with traces, code and limits.
  9. 85 Shell Sort, Timsort and Hybrid Sorts Learn Shell sort gap sequences, how Python's Timsort uses runs and merging, and how introsort mixes quick, heap and insertion sort. Includes comparison counts.
  10. 86 Sorting in Libraries - qsort, std::sort, Arrays.sort and sorted() What the sort functions of C, C++, Java, Python, JavaScript, Go and Rust really do: algorithms, stability, comparator rules and the bugs that bad comparators cause.
  11. 87 Sorting Problems and Applications Solve classic sorting problems in Python: merge intervals, meeting rooms, k-th largest, a custom comparator, sort by frequency and external sorting.
  12. 88 Cycle, Gnome, Pancake and Bitonic Sort Meet four unusual sorting algorithms in Python: gnome sort, cycle sort with minimal writes, pancake sorting with prefix flips, and bitonic sort networks.

Trees

  1. 89 Trees Learn what a tree is: root, leaf, depth, height, subtrees, n-ary trees, ways to store them in Python, real uses and how recursion walks a tree.
  2. 90 Binary Trees Learn binary trees from scratch in Python: the node class, full, complete, perfect and balanced trees, array storage, building trees and counting nodes and height.
  3. 91 Tree Traversals Learn preorder, inorder and postorder tree traversal in Python, both recursive and iterative, plus Morris traversal and rebuilding a tree from two traversals.
  4. 92 N-ary Trees: Depth, Diameter, Mirror, Serialize Work with trees where a node has any number of children: height, diameter, mirror, serialization, and the first-child/next-sibling trick that turns them binary.
  5. 93 Level-Order Traversal and Tree BFS Master breadth-first search on binary trees in Python: level-order traversal with a queue, level lists, zigzag, right-side view, minimum depth and tree width.
  6. 94 Binary Search Trees Build a binary search tree in Python from scratch: insert, search, min and max, delete with all three cases, successor, validation and the degenerate worst case.
  7. 95 Common Tree Problems Solve classic binary tree problems in Python, brute force first: diameter, lowest common ancestor, path sum, same and symmetric tree, invert, serialize, subtree.
  8. 96 BST Problems: Merge, Fix Swapped, Largest BST, List to BST Four classic BST problems in Python: build a balanced BST from a sorted list, merge two BSTs, repair a BST with two swapped nodes, and find the largest BST in a tree.
  9. 97 Binary Tree Problems: Flatten, Candies, Ancestor Difference, Lonely Nodes Solve classic binary tree problems in Python: flatten to a linked list, distribute candies, node-ancestor maximum difference, nodes without siblings and BST to min-heap.
  10. 98 Self-Balancing Trees: AVL Learn AVL trees in Python: balance factor, left and right rotations, the LL, RR, LR and RL cases, insert and delete with rebalancing, and the height guarantee.
  11. 99 Red-Black Trees, Splay Trees and Treaps Learn how red-black trees, splay trees and treaps keep a binary search tree balanced, with rotations, a red-black insert and a treap built from scratch in Python.
  12. 100 Scapegoat Trees and Self-Organizing Lists Two structures that fix themselves lazily: scapegoat trees rebuild a lopsided subtree, and self-organizing lists reorder with move-to-front, transpose and count.
  13. 101 B-Trees and B+ Trees Learn why databases use B-trees and B+ trees: disk pages, order, search, insert with node splits, range scans, and a small B-tree you can run in Python.
  14. 102 Ternary Search Trees Learn the ternary search tree: a trie that stores one character per node with three links. Insert, search, delete and autocomplete in Python, and compare it with a trie.
  15. 103 Binary Lifting and Lowest Common Ancestor Learn binary lifting in Python: build jump pointers in O(n log n), find the k-th ancestor and the lowest common ancestor in O(log n), and compute tree distances.
  16. 104 Cartesian Trees Learn the Cartesian tree in Python: build it from an array in O(n) with a stack, see how it answers range minimum queries and why a treap is a Cartesian tree.
  17. 105 Tree Isomorphism and Tree Hashing Decide whether two trees have the same shape: build canonical forms, assign subtree ids, handle unrooted trees with centers, and find duplicate subtrees.

Heaps

  1. 106 Binary Heaps Learn binary heaps in Python: the complete tree stored in a list, index formulas, min and max heaps, sift up and down, and why build-heap runs in O(n).
  2. 107 Heaps in Python: heapq Use Python's heapq module: heappush, heappop, heapify, nlargest, nsmallest, merge, max-heaps, tuple priorities, tie-breaking counters and custom objects.
  3. 108 Top-K and Streaming Problems Solve top-k problems in Python with a size-k heap: k largest numbers, kth largest in a stream, k most frequent words and k closest points, with complexity.
  4. 109 Running Median and Two Heaps Find the median of a data stream in O(log n) per number with two heaps in Python. Compare brute force, bisect and the two-heap pattern, plus the sliding window idea.
  5. 110 Merging K Sorted Lists Merge k sorted lists with a min-heap in O(N log k) time: brute force first, the heap solution, heapq.merge, external merge sort and the smallest range problem.
  6. 111 Fibonacci, Binomial and d-ary Heaps Learn d-ary, binomial and Fibonacci heaps in Python: how they differ from a binary heap, mergeable heaps, decrease-key, amortized costs and when they matter.

Tries and Range Queries

  1. 112 Tries Learn the trie (prefix tree) in Python: insert, search and starts_with, dict vs array children, delete, counting words by prefix, memory use and complexity.
  2. 113 Trie Applications Put tries to work in Python: autocomplete with top-k, longest common prefix, Word Search II, maximum XOR pair with a bitwise trie and compressed radix trees.
  3. 114 Segment Trees Learn segment trees in Python: build, range sum and min queries, point update, an iterative array version and lazy propagation for range updates, with complexity.
  4. 115 Fenwick Tree (Binary Indexed Tree) Learn the Fenwick tree (binary indexed tree) in Python: lowbit, update and prefix query in O(log n), range sums, counting inversions and a 2D version.
  5. 116 Sparse Tables and RMQ Answer range minimum queries in O(1) with a sparse table in Python. Build it in O(n log n), learn why overlap works for idempotent operations, and see LCA via RMQ.
  6. 117 Square Root Decomposition and Mo's Algorithm Learn square root decomposition in Python: split data into blocks for fast range queries and updates, then use Mo's algorithm to answer offline queries efficiently.
  7. 118 Heavy-Light Decomposition Learn heavy-light decomposition in Python: split a tree into heavy chains, map them onto an array and answer path max queries and updates in O(log^2 n).
  8. 119 Merge Sort Tree and Wavelet Trees Answer 'how many values are below x' and 'what is the k-th smallest' in any array range using a merge sort tree and a wavelet tree, with Python code and diagrams.

Graphs

  1. 120 Graphs Understand graphs from scratch: vertices, edges, directed and undirected, weighted, degree, paths, cycles, DAGs and connectivity, with Python code you can run.
  2. 121 Graph Representations Learn how to store a graph in Python: adjacency matrix, adjacency list, edge list and grids. Compare memory and speed, build graphs from input, and choose well.
  3. 122 Breadth-First Search Learn breadth-first search in Python: queue and visited set, levels, shortest paths in unweighted graphs, path reconstruction, grid mazes and O(V+E) complexity.
  4. 123 Depth-First Search Learn depth-first search in Python: recursive and iterative versions, discovery and finish times, path finding, applications, and how DFS compares with BFS.
  5. 124 Connected Components and Flood Fill Count connected components, solve the number-of-islands problem, flood fill an image and run multi-source BFS (rotting oranges), with Python code you can run.
  6. 125 BFS Puzzles: Water Jug, Snakes and Ladders, Combination Locks Solve classic puzzles with breadth-first search in Python by turning each configuration into a graph state: water jugs, snakes and ladders and a combination lock.
  7. 126 Graph Oddities: Universal Sink, Degree Sequences, Petersen, Random Graphs Learn five classic graph topics in Python: the O(V) universal sink search, Havel-Hakimi degree sequences, the Petersen graph, Erdos-Renyi random graphs and offline dynamic connectivity.
  8. 127 Cycle Detection Detect cycles in undirected graphs with the parent trick, in directed graphs with three colors, and in functional graphs with Floyd's tortoise and hare.
  9. 128 Topological Sort Order tasks so every dependency comes first. Learn Kahn's algorithm, DFS topological sort, the course schedule problem and longest paths in a DAG.
  10. 129 Bipartite Graphs and Coloring Check whether a graph is bipartite with BFS 2-coloring, understand the odd-cycle rule, solve possible bipartition, try bipartite matching and greedy coloring.
  11. 130 Union-Find (Disjoint Sets) Learn union-find, also called disjoint set union: find with path compression, union by size, near constant time, counting components and redundant connections.
  12. 131 Stable Marriage and the Hungarian Algorithm Match two groups with the Gale-Shapley stable marriage algorithm and solve the minimum-cost assignment problem with the Hungarian algorithm in O(n^3) in Python.
  13. 132 Karger's Algorithm and Global Minimum Cut Find the global minimum cut of a graph with Karger's random contraction algorithm in Python: how contraction works, its success probability and how to boost it.
  14. 133 Gomory-Hu Tree Build a Gomory-Hu tree with Gusfield's algorithm in Python: n-1 max-flow runs give every pairwise minimum cut, and the lightest tree edge is the global min cut.

Shortest Paths and Spanning Trees

  1. 134 Dijkstra's Algorithm Learn Dijkstra's shortest path algorithm step by step: relaxation, a heapq version, path reconstruction, network delay time and why negative edges break it.
  2. 135 Bellman-Ford Algorithm Learn Bellman-Ford step by step: relax every edge V-1 times, handle negative weights, detect and print negative cycles, and solve cheapest flights with k stops.
  3. 136 Floyd-Warshall Algorithm Understand Floyd-Warshall all-pairs shortest paths: the DP idea, three nested loops, path reconstruction, negative cycles, transitive closure and city problems.
  4. 137 Minimum Mean Weight Cycle and Walks of Length k Find the cycle with the smallest average edge weight using Karp's algorithm in Python, and count or minimise walks of exactly k edges with matrix powers over semirings.
  5. 138 0-1 BFS, A* and Other Shortest Paths Faster shortest paths for special graphs: 0-1 BFS with a deque, DAG relaxation, A* with a heuristic on a grid, bidirectional search and Johnson's reweighting.
  6. 139 Minimum Spanning Trees: Kruskal and Prim Learn minimum spanning trees: cut and cycle properties, Kruskal's algorithm with union-find, Prim's algorithm with a heap, clustering, and when to use each.
  7. 140 Boruvka's Algorithm and MST Variants Learn Boruvka third MST algorithm in Python, then solve MST variants: the minimum bottleneck path, the second-best spanning tree and the maximum spanning tree.
  8. 141 Counting Spanning Trees: Kirchhoff, Cayley, Prufer and Reverse-Delete Count spanning trees with Kirchhoff's matrix-tree theorem and Cayley's formula, encode labelled trees as Prufer sequences, and build an MST with reverse-delete in Python.
  9. 142 Strongly Connected Components Find strongly connected components in a directed graph with Kosaraju's two-pass DFS and Tarjan's low-link method, then build the condensation DAG in Python.
  10. 143 2-SAT with Strongly Connected Components Solve 2-SAT in linear time with Python: build the implication graph, find strongly connected components and read a satisfying assignment from component order.
  11. 144 Bridges and Articulation Points Find bridges, articulation points and biconnected components in an undirected graph with one DFS and low-link values, including an iterative version for big graphs.
  12. 145 Maximum Flow and Matching Learn network flow in Python: residual graphs, Ford-Fulkerson, Edmonds-Karp, the max-flow min-cut theorem and how to solve bipartite matching with flow.
  13. 146 Push-Relabel and Min-Cost Flow Compute maximum flow with push-relabel and minimum-cost flow with successive shortest paths in Python, verified against Edmonds-Karp and brute force.
  14. 147 Eulerian and Hamiltonian Paths Learn Euler paths and circuits with the degree test and Hierholzer's algorithm, then see why Hamiltonian paths are hard, with backtracking and a TSP bitmask preview.

Dynamic Programming

  1. 148 Dynamic Programming Learn dynamic programming from scratch in Python: overlapping subproblems, optimal substructure, and Fibonacci solved three ways with real call counts.
  2. 149 Memoization vs Tabulation Compare top-down memoization and bottom-up tabulation in Python with one worked problem, a state-definition recipe, space optimization and recursion limits.
  3. 150 One-Dimensional DP Practice one-dimensional dynamic programming in Python: climbing stairs, house robber, min-cost stairs, decode ways, max product subarray and jump game.
  4. 151 The 0/1 Knapsack Problem Master the 0/1 knapsack problem in Python: brute force, the DP table, the 1D space trick, rebuilding the chosen items, subset sum, equal partition and target sum.
  5. 152 Unbounded Knapsack and Coin Change Solve coin change with dynamic programming in Python: fewest coins, counting ways, combinations vs permutations, rod cutting and unbounded knapsack.
  6. 153 Longest Increasing Subsequence Learn the longest increasing subsequence in Python: the O(n^2) DP, the O(n log n) bisect method, rebuilding the sequence, counting and common variants.
  7. 154 LCS and Edit Distance Master two classic string DPs in Python: longest common subsequence and substring, plus Levenshtein edit distance, with tables and reconstruction.
  8. 155 DP on Grids Learn grid dynamic programming in Python: unique paths, minimum path sum, obstacles, maximal square and the dungeon game, from brute force to DP.
  9. 156 DP on Strings Solve classic string DP problems in Python: palindromic subsequence, palindrome cuts, word break, wildcard and regex matching, and interleaving.
  10. 157 Interval and Matrix-Chain DP Learn interval dynamic programming in Python: matrix-chain multiplication, burst balloons, merging stones and optimal BST with the split-point template.
  11. 158 Bitmask DP Learn bitmask dynamic programming in Python: store subsets as integers, then solve the assignment problem, Held-Karp TSP and path counting step by step.
  12. 159 DP on Trees and DAGs Learn dynamic programming on trees and DAGs in Python: subtree states, house robber III, tree diameter, rerooting for all roots and longest paths in a DAG.
  13. 160 Optimising DP Speed up and shrink dynamic programming in Python: rolling arrays, prefix-sum speedups, monotonic deque optimisation and a map of the named DP optimisations.
  14. 161 Optimal Game Strategy, Painter's Partition and Bridge and Torch Solve three classic DP puzzles in Python: the coin-row game with optimal players, painter's partition by DP, and the bridge-and-torch crossing problem.
  15. 162 Weighted Job Scheduling and Largest Divisible Subset Solve weighted job scheduling with DP and binary search, then the largest divisible subset with a LIS-style chain DP. Python code with rebuilt answers.
  16. 163 Digit DP Learn digit DP in Python: count the numbers up to N whose digits satisfy a rule using position, tight flag and state, with memoization and worked examples.
  17. 164 Word Wrap, Box Stacking and Tile Stacking Learn three DP problems in Python: optimal line breaking with the word wrap cost, box stacking as a 3D longest increasing chain, and bounded-run tile stacking.
  18. 165 Stock Buy and Sell with k Transactions Solve the whole stock buy-and-sell family in Python: one trade, unlimited trades, at most 2 or k transactions, cooldown and fee, with one state-machine DP.
  19. 166 Egg Dropping, Rod Cutting and Classic DP Puzzles Solve classic dynamic programming puzzles in Python: rod cutting, the egg dropping problem with a fast inverted state, domino tiling and counting binary trees.

Greedy Algorithms

  1. 167 Greedy Algorithms Understand greedy algorithms in Python: the greedy choice property, exchange-argument proofs, coin change counterexamples and how to test a greedy idea.
  2. 168 Interval Scheduling and Meeting Rooms Solve interval problems in Python: activity selection, minimum platforms and meeting rooms, merge intervals and non-overlapping intervals with greedy sorting.
  3. 169 Huffman Coding Learn Huffman coding in Python: prefix-free codes, building the tree with a heap, encoding and decoding text, compression ratios and why the greedy is optimal.
  4. 170 Greedy Problems Practice greedy algorithms in Python: fractional knapsack, jump game, gas station, candy, task scheduler and assign cookies, each with a brute force first.
  5. 171 Job Sequencing, Egyptian Fractions and Pairing Problems Solve job sequencing with deadlines (heap and union-find), Egyptian fractions, policemen and thieves and mice to holes with greedy Python code.
  6. 172 Minimize Cash Flow, Water Connection and Cutting a Board Greedy Python solutions for settling group debts with two heaps, finding pipe chains in the water connection problem, and cutting a board at minimum cost.
  7. 173 Greedy Approximation: Set Cover, Bin Packing, k-Center and TSP Learn how greedy algorithms approximate NP-hard problems: set cover, bin packing, k-center, TSP via MST and shortest superstring, with Python code.
  8. 174 Greedy in Operating Systems: Memory Fit, SJF and Page Replacement See greedy ideas inside an operating system: first, best and worst fit memory allocation, shortest job first scheduling, and FIFO, LRU and optimal page replacement.
  9. 175 Greedy vs Dynamic Programming Compare greedy and dynamic programming in Python on the same problems: coin change, knapsack and interval scheduling. Learn when greedy fails and how to decide.

Math and Bit Manipulation

  1. 176 Bit Manipulation Learn bit manipulation in Python: AND, OR, XOR, shifts, two's complement, set and clear bits, counting bits, power of two, single number and bitmask subsets.
  2. 177 Number Theory Basics Number theory in Python for DSA: Euclid's gcd and lcm, primality tests, the sieve of Eratosthenes, prime factorization, modular arithmetic and modular inverse.
  3. 178 Digit and Number Puzzles Solve classic number exercises in Python: Armstrong and perfect numbers, digital roots, divisibility rules from digits, and finding repeating decimals of fractions.
  4. 179 Factorials, Legendre's Formula and Zeckendorf Count trailing zeros of n!, find the power of a prime in n! with Legendre's formula, get the last nonzero digit and write numbers as sums of Fibonacci numbers.
  5. 180 Fast Exponentiation and Matrix Power Compute powers in O(log n) with binary exponentiation in Python, add a modulus, then use matrix power to get Fibonacci numbers and linear recurrences fast.
  6. 181 Fast Doubling Fibonacci and Newton's Method Compute Fibonacci numbers in O(log n) with fast doubling, find integer square roots exactly and solve equations numerically with Newton's method in Python.
  7. 182 Combinatorics and Counting Count without listing: product and sum rules, permutations, combinations, Pascal's triangle, Catalan numbers and inclusion-exclusion, with math.comb and perm.
  8. 183 Lucas' Theorem, Stirling, Bell and Catalan Numbers Compute nCr mod a small prime with Lucas' theorem, then count set partitions and balanced structures with Stirling, Bell and Catalan numbers in Python.
  9. 184 Burnside's Lemma and Counting Necklaces Count objects up to symmetry with Burnside lemma in Python: necklaces under rotation, bracelets with reflection and grid colorings, checked by brute force.
  10. 185 Randomized Algorithms Learn randomized algorithms in Python: Fisher-Yates shuffle, reservoir sampling, randomized quickselect and the difference between Monte Carlo and Las Vegas.
  11. 186 Computational Geometry Basics Learn computational geometry in Python: the cross product, orientation tests, segment intersection, Andrew's convex hull and the shoelace polygon area.
  12. 187 Sieve of Eratosthenes, Segmented Sieve and Miller-Rabin Generate primes with the sieve of Eratosthenes, extend it with a segmented sieve for huge ranges, and test big numbers with the Miller-Rabin primality test in Python.
  13. 188 Inclusion-Exclusion, Euler's Totient and Mobius Function Count with inclusion-exclusion, build totient and Mobius sieves in Python, count coprime pairs fast and use Mobius inversion to undo divisor sums.
  14. 189 Fermat Test, Mersenne Primes and Pollard's Rho Learn the Fermat primality test and Carmichael numbers, the Lucas-Lehmer test for Mersenne primes, the idea behind AKS, and Pollard's rho to factor big integers.
  15. 190 Chinese Remainder Theorem and Modular Inverse Compute modular inverses with the extended Euclidean algorithm and solve systems of congruences with the Chinese Remainder Theorem, including non-coprime moduli, in Python.
  16. 191 Primitive Roots and Discrete Logarithm (Baby-Step Giant-Step) Find multiplicative orders and primitive roots modulo a prime, then solve a^x = b mod p with the baby-step giant-step algorithm in O(sqrt p) time in Python.
  17. 192 FFT and Polynomial Multiplication Multiply polynomials and big numbers in O(n log n) with the Fast Fourier Transform and the exact Number Theoretic Transform. Clear Python code and diagrams.
  18. 193 Gaussian Elimination and Linear Systems Solve linear systems with Gaussian elimination in Python: exact fractions, partial pivoting, determinants, modular arithmetic and the XOR basis over GF(2).
  19. 194 Gray Code and Bit Tricks Generate Gray code with i ^ (i >> 1), decode it, walk all subsets by flipping one bit at a time, enumerate submasks and use lowest-set-bit tricks in Python.

Advanced Topics

  1. 195 Skip Lists Learn how a skip list works and build one in Python: layered linked lists with coin-flip levels give expected O(log n) search, insert and delete.
  2. 196 Designing Data Structures Learn to design custom data structures in Python: min-stack, O(1) randomized set, time-based key-value store, snapshot array and iterator design.
  3. 197 P, NP and Hard Problems Understand P, NP and NP-complete problems with Python: verify vs solve, SAT, subset sum, TSP, clique, reductions and a 2-approximation for vertex cover.
  4. 198 Online and Streaming Algorithms Learn online and streaming algorithms in Python: one-pass Boyer-Moore majority vote, count-min sketch, running and sliding statistics and reservoir sampling.
  5. 199 Parallel and External Algorithms Learn external merge sort, the MapReduce idea, work and span for parallel algorithms, and the cache-oblivious trick, with Python simulations you can run.
  6. 200 Advanced Amortized Structures Go beyond dynamic arrays. Study splay tree amortization, the inverse Ackermann bound for union-find, ropes for text editors and persistent stacks in Python.
  7. 201 Centroid Decomposition Learn centroid decomposition in Python: split a tree at its centroid, build the centroid tree of depth O(log n) and answer nearest-marked-node queries.
  8. 202 Interval Trees, k-d Trees and Quadtrees Learn spatial and interval queries: find overlapping intervals with an interval tree, nearest neighbors with a k-d tree, and range searches with a quadtree, in Python.
  9. 203 Game Theory: Nim and Sprague-Grundy Solve two-player games in Python with winning and losing positions, minimax, Nim and the XOR rule, and Grundy numbers with mex for sums of games.
  10. 204 Celebrity Problem and Skyline Two classic interview problems in Python: find the celebrity with O(n) elimination, and compute the city skyline with a sweep line and a max-heap.
  11. 205 Sweep Line Algorithms Learn the sweep line technique: turn intervals and rectangles into sorted events, then scan once to count overlaps, find busy times and compute union area.
  12. 206 Suffix Automaton Build a suffix automaton in linear time, check substring queries in O(m), and count distinct substrings and occurrences, with fully runnable Python code.
  13. 207 van Emde Boas Trees and Y-fast Tries Learn how van Emde Boas trees find successors and predecessors of integer keys in O(log log u), build one in Python, and see how Y-fast tries save space.
  14. 208 Minimax, Alpha-Beta Pruning and Zobrist Hashing Build a perfect tic-tac-toe player in Python with minimax, speed it up with alpha-beta pruning and add a transposition table keyed by Zobrist hashing.
  15. 209 Pick's Theorem, Half-Plane Intersection and Bresenham Count lattice points with Pick's theorem, find the region cut out by half-planes with polygon clipping and draw exact integer lines with Bresenham in Python.
  16. 210 Palindromic Tree (Eertree) Build an eertree in Python: add characters one at a time, follow suffix links, and count every distinct palindromic substring of a string in linear time.
  17. 211 Pseudo-Random Generators and Simulated Annealing Build linear congruential and xorshift random number generators, test their quality, then use random moves and a cooling schedule in simulated annealing.

Projects

  1. 212 Project: Autocomplete Engine Build a search-box autocomplete engine in stages. Start with brute force, move to a trie, cache top suggestions per node, learn from clicks, and test it.
  2. 213 Project: Route Planner Build a route planner on a city map in stages. Model the roads as a graph, find fewest roads with BFS, shortest distance with Dijkstra, then speed up with A*.
  3. 214 Project: Text Editor Buffer with Undo Build the core of a text editor in stages. Compare string slicing with a gap buffer, add undo and redo stacks with commands, then test it against a simple model.
  4. 215 Project: Task Scheduler Build a task scheduler with dependencies in stages. Use topological sort to order tasks, a priority queue to pick the next one, and a simulation for many workers.
  5. 216 Project: Spell Checker Build a spell checker in stages. Start with a hash set, add edit distance, generate candidate edits, speed up search with a BK-tree, and test every version.
  6. 217 Project: Real-time Leaderboard Build a game leaderboard in stages. Compare a dict with sorting, a bisect-sorted list and a Fenwick tree for fast ranks, top-k queries and live updates.

Practice and Review

  1. 218 Problem Patterns Cheat Sheet Match problem signals to the right technique. A Python cheat sheet with runnable templates for two pointers, windows, BFS, DP, heaps, backtracking and more.
  2. 219 Choosing the Right Data Structure Pick the right data structure by the operations you need. Decision tables, Python built-ins versus custom code, counted comparisons and real system examples.
  3. 220 Practice Problems: Arrays, Strings and Hashing Twelve graded problems on arrays, strings and hash maps, from Two Sum to trapping rain water. Each has a hint, a brute force, the fast solution and tests.
  4. 221 Practice Problems: Trees, Graphs and DP Twelve graded problems on trees, graphs and dynamic programming, from tree depth to Word Ladder and LCS. Each has a hint, a brute force, a solution and tests.
  5. 222 DSA Interview Questions and Answers Forty data structures and algorithms interview questions with clear short answers: complexity, arrays, hashing, trees, graphs, sorting, DP, and runnable Python.
  6. 223 Coding Interview Preparation Plan An eight-week, pattern-by-pattern plan for algorithm interviews: what to study each week, how to practice, how to run mock interviews and track progress.
  7. 224 Practice Sets by Topic (Arrays, Trees, Graphs, DP) Curated practice sets for arrays, trees, graphs and dynamic programming. Each problem has a difficulty, a hint and the pattern it trains, plus worked samples.
  8. 225 The Top 100 Interview Problems, Mapped by Topic A topic-by-topic map of 100 must-know coding interview problems, each with the technique that solves it and the lesson that teaches it. Includes a Python practice planner.