The Algorithms - Python Python TheAlgorithms/Python

The Algorithms - Python Tours

52 tours available

Getting Started with Your First Contribution to TheAlgorithms/Python

beginner

Walk the README disclaimer, the CONTRIBUTING.md algorithm requirements, the canonical insertion_sort file shape, the auto-generated DIRECTORY.md, the pytest --doctest-modules gate, and the path to deeper algorithm tours.

6 stops ~16 min
Prerequisites: Python 3.14 installed locally, Comfort reading short Python files with type hints, Familiarity with git and GitHub pull requests
contributiononboardingpythonalgorithmstheAlgorithms

Navigating TheAlgorithms/Python: A Tour of the 43 Categories

beginner

Sample one canonical algorithm from each major category (a sort, a search, a graph traversal, a DP class, a cipher) and end on the autoapi_dirs list that names every category.

7 stops ~18 min
Prerequisites: Comfort reading short Python files with type hints, No prior knowledge of any specific algorithm required
navigationoverviewpythonalgorithmstheAlgorithms

How Bubble Sort Works

intermediate

Compare adjacent elements, swap if out of order, repeat. The algorithm that appears in every first-year course because the swapping motion is easy to picture.

6 stops ~14 min
Prerequisites: Comfort reading nested Python for loops, No prior knowledge of bubble sort required
sortingalgorithmpythonalgorithmstheAlgorithms

How Insertion Sort Works

intermediate

Pick the next element, shift everything larger one position right, drop the element into the gap. The algorithm that outperforms quicksort on small runs.

6 stops ~14 min
Prerequisites: Comfort reading Python while loops with index arithmetic, No prior knowledge of insertion sort required
sortingalgorithmpythonalgorithmstheAlgorithms

How Selection Sort Works

intermediate

Find the minimum of the unsorted region, swap it to the front, repeat. O(n squared) always, but only O(n) swaps total.

5 stops ~10 min
Prerequisites: Comfort reading nested Python for loops with index variables, No prior knowledge of selection sort required
sortingalgorithmpythonalgorithmstheAlgorithms

How Mergesort Works

intermediate

Split the list in half, sort each half recursively, merge the two sorted halves. The first algorithm written for a stored-program computer.

6 stops ~14 min
Prerequisites: Comfort reading recursive Python, Familiarity with list slicing syntax, No prior knowledge of mergesort required
sortingalgorithmpythonalgorithmstheAlgorithms

How Quicksort Works

intermediate

A random pivot, a partition into lesser and greater, two recursive calls. The 1959 algorithm that still drives most stdlib sorts.

6 stops ~14 min
Prerequisites: Comfort reading Python list comprehensions, Familiarity with recursion and the call stack, No prior knowledge of quicksort required
sortingalgorithmpythonalgorithmstheAlgorithms

How Heapsort Works

intermediate

Build a max-heap over the array, then repeatedly swap the root to the back and restore the heap. O(n log n) worst case with no extra memory.

6 stops ~16 min
Prerequisites: Comfort reading Python with index arithmetic, Familiarity with recursion in a helper function, No prior knowledge of heapsort required
sortingalgorithmpythonalgorithmstheAlgorithms

How Radix Sort Works

intermediate

Sort by least significant digit, then next digit, repeat. Non-comparison sort that runs in O(d times n) rather than O(n log n).

5 stops ~12 min
Prerequisites: Comfort reading Python integer arithmetic and list comprehensions, No prior knowledge of radix sort or bucket sort required
sortingalgorithmpythonalgorithmstheAlgorithms

How Counting Sort Works

intermediate

No comparisons, no pivots. Count key frequencies, prefix-sum them, then place each element at its exact output index in one backward pass.

6 stops ~15 min
Prerequisites: Comfort reading Python list comprehensions and the range() function, Familiarity with the idea of an array index as a position, No prior knowledge of counting sort required
sortingalgorithmpythonalgorithmstheAlgorithms

How Linear Search Works

intermediate

Scan every element in order, return the index on match, return -1 on miss. The lower bound for searching unsorted data.

5 stops ~12 min
Prerequisites: Comfort reading Python for loops and the enumerate() built-in, Familiarity with recursion and the call stack, No prior knowledge of search algorithms required
searchalgorithmpythonalgorithmstheAlgorithms

How Binary Search Works

intermediate

Halve the search space on every step. The 1946 algorithm that still trips up professionals on overflow and off-by-one errors.

6 stops ~16 min
Prerequisites: Comfort reading Python while loops, Familiarity with recursion and the call stack, No prior knowledge of binary search required
searchalgorithmpythonalgorithmstheAlgorithms

How Jump Search Works

intermediate

Jump through sorted data in square-root-sized blocks, then linear-search the candidate block. O(sqrt(n)) with no recursion, no pivots.

5 stops ~14 min
Prerequisites: Comfort reading Python while loops and the math module, Familiarity with sorted arrays and index arithmetic, No prior knowledge of jump search required
searchalgorithmpythonalgorithmstheAlgorithms

How BFS Works

intermediate

Visit every neighbor before going deeper. The FIFO queue invariant that guarantees shortest-path distances on unweighted graphs.

6 stops ~14 min
Prerequisites: Comfort reading Python classes and methods, Familiarity with the concept of a queue (first in, first out), No prior knowledge of graph traversal required
searchalgorithmpythonalgorithmstheAlgorithms

How DFS Works

intermediate

Follow a path as deep as it goes before backtracking. The iterative stack-based implementation that mirrors the recursive structure without blowing the call stack.

5 stops ~12 min
Prerequisites: Comfort reading Python while loops and list operations, A mental model of stacks (last in, first out), No prior knowledge of depth-first search required
searchalgorithmpythonalgorithmstheAlgorithms

How Dijkstra's Algorithm Works

intermediate

A min-heap of (cost, node) tuples, a visited set, and a single relaxation loop. The 1956 algorithm at the core of OSPF and IS-IS routing.

7 stops ~18 min
Prerequisites: Familiarity with Python's heapq module or any binary heap, Comfort reading nested loops over an adjacency dict, No prior knowledge of shortest-path algorithms required
pythonalgorithmstheAlgorithms

How A* Search Works

intermediate

Combine actual path cost with a heuristic estimate of remaining distance. The 1968 algorithm built for a robot, now in every map and game engine.

6 stops ~18 min
Prerequisites: Familiarity with Python lists and nested loops, A basic mental model of graph traversal (BFS or Dijkstra), No prior knowledge of A* required
pythonalgorithmstheAlgorithms

How Bellman-Ford Works

intermediate

Relax every edge V-1 times, then run one more pass to detect negative cycles. The algorithm Dijkstra cannot replace.

6 stops ~16 min
Prerequisites: Familiarity with Python list comprehensions and dict access, A basic mental model of a weighted directed graph, No prior knowledge of shortest-path algorithms required
pythonalgorithmstheAlgorithms

How Kruskal's Algorithm Works

intermediate

Sort edges by weight, then add each one unless it creates a cycle. Union-find with path compression in 46 lines.

5 stops ~14 min
Prerequisites: Familiarity with Python sorted() and lambda key functions, A basic mental model of a graph as nodes connected by edges with weights, No prior knowledge of spanning trees or union-find required
pythonalgorithmstheAlgorithms

How Fibonacci DP Works

intermediate

Cache the sequence on a class instance, extend it on demand, return a slice. The canonical example of memoization replacing exponential recursion.

5 stops ~14 min
Prerequisites: Comfort reading Python classes and list indexing, No prior knowledge of dynamic programming required
pythonalgorithmstheAlgorithms

How the 0/1 Knapsack DP Works

intermediate

Fill a capacity-by-item table bottom-up, then trace back through it to recover which items go in the bag.

6 stops ~20 min
Prerequisites: Comfort reading nested Python loops, Familiarity with the concept of recursion and memoization, No prior knowledge of dynamic programming or knapsack required
pythonalgorithmstheAlgorithms

How Longest Common Subsequence Works

intermediate

A 2-D DP table, one recurrence, and a traceback walk. The algorithm at the core of diff, git-merge, and DNA sequence alignment.

6 stops ~18 min
Prerequisites: Comfort reading nested Python loops, Familiarity with two-dimensional lists, No prior knowledge of dynamic programming required
pythonalgorithmstheAlgorithms

How Edit Distance Works

intermediate

Count the minimum insertions, deletions, and substitutions to transform one string into another. The 1965 algorithm behind spell-check, fuzzy search, and DNA alignment.

6 stops ~18 min
Prerequisites: Comfort reading Python classes and private methods, Familiarity with recursion and memoization, No prior knowledge of dynamic programming required
pythonalgorithmstheAlgorithms

How the Sieve of Eratosthenes Works

intermediate

Mark every multiple of each found prime starting at its square. What remains is a list of primes, produced in O(n log log n).

5 stops ~14 min
Prerequisites: Comfort reading Python while loops and range expressions, Basic familiarity with the concept of prime numbers, No prior knowledge of the sieve required
pythonalgorithmstheAlgorithms

How the Caesar Cipher Works

intermediate

A modular shift over an alphabet, mirrored to decrypt, exhausted to brute-force. The oldest attested cipher in the Western record.

6 stops ~16 min
Prerequisites: Comfort reading Python string operations, Familiarity with the modulo operator, No prior knowledge of cryptography required
cryptographycipherpythonalgorithmstheAlgorithms

How RSA Encryption Works

intermediate

Split the message into fixed-size integer blocks, raise each block to a modular power, and undo it with the private exponent.

6 stops ~20 min
Prerequisites: Familiarity with modular arithmetic (the % operator), Comfort reading Python functions that read and write files, No prior knowledge of public-key cryptography required
cryptographycipherpythonalgorithmstheAlgorithms

How SHA-1 Works

intermediate

Pad the message, split into 512-bit blocks, expand each block to 80 words, run 80 rounds of bit operations, accumulate five 32-bit words into a 160-bit digest.

6 stops ~20 min
Prerequisites: Comfort reading Python bitwise operators (<<, >>, |, ^, &, ~), Familiarity with hexadecimal notation, No prior knowledge of cryptographic hash functions required
pythonalgorithmstheAlgorithms

How MD5 Works

intermediate

Four 32-bit state words, 64 rounds, a sin-derived constant table. The 1991 algorithm that still shows up in checksums everywhere.

6 stops ~20 min
Prerequisites: Familiarity with bitwise AND, OR, XOR, and NOT operations, Basic understanding of hexadecimal and byte representations, No prior knowledge of cryptographic hash functions required
pythonalgorithmstheAlgorithms

How the Knuth-Morris-Pratt Algorithm Works

intermediate

Preprocess the pattern into a failure array, then scan the text without backtracking. The 1977 algorithm that makes grep and DNA search O(n+m).

6 stops ~16 min
Prerequisites: Comfort reading Python while loops with two index variables, Familiarity with string indexing and slicing, No prior knowledge of string-matching algorithms required
stringsalgorithmpythonalgorithmstheAlgorithms

How Rabin-Karp String Matching Works

intermediate

Hash the pattern, slide a rolling hash across the text, confirm on match. The 1987 algorithm that makes multi-pattern search practical.

5 stops ~14 min
Prerequisites: Comfort reading Python for-loops with modular arithmetic, Familiarity with the concept of a hash function producing integers, No prior knowledge of rolling hashes or string-matching algorithms required
pythonalgorithmstheAlgorithms

How a Bloom Filter Works

intermediate

A bitarray, two hash functions, and a membership check that never gives false-negatives. Burton Bloom's 1970 data structure still in production databases.

6 stops ~14 min
Prerequisites: Familiarity with Python bitwise operators and integer bit representations, Basic understanding of hash functions as deterministic black boxes, No prior knowledge of probabilistic data structures required
pythonalgorithmstheAlgorithms

How an LRU Cache Works

intermediate

A doubly-linked list plus a hashmap gives O(1) get and put. The eviction policy at the core of CPU caches, browser caches, and functools.lru_cache.

6 stops ~18 min
Prerequisites: Comfort reading Python generics syntax with TypeVar, Familiarity with doubly-linked lists and hash dictionaries, No prior knowledge of cache eviction policies required
pythonalgorithmstheAlgorithms

Sorting Algorithms in TheAlgorithms/Python

beginner

Seven sorting strategies side by side: from the classroom bubble loop to radix buckets.

7 stops ~14 min
Prerequisites: Comfort reading Python for-loops and list indexing, Familiarity with the concept of O(n) and O(n log n) complexity, No prior knowledge of any specific sort required
category-toursortspythonalgorithmstheAlgorithms

Search Algorithms in TheAlgorithms/Python

beginner

Seven search strategies from a simple scan to partition-based selection, each with a different trade-off.

7 stops ~14 min
Prerequisites: Comfort reading Python while-loops and index arithmetic, Basic familiarity with sorted collections and what O(log n) means, No prior knowledge of any specific search algorithm required
category-toursearchespythonalgorithmstheAlgorithms

Cipher Algorithms in TheAlgorithms/Python

intermediate

Seven ciphers from ancient Rome to Diffie-Hellman: each a different answer to the question of what makes a message unreadable.

7 stops ~16 min
Prerequisites: Comfort reading Python loops, modular arithmetic, and string indexing, Familiarity with the concept of a key in symmetric encryption, No prior cryptography knowledge required
category-tourcipherspythonalgorithmstheAlgorithms

Hash Functions in TheAlgorithms/Python

beginner

Six hash algorithms from a 13-byte checksum to 256-bit cryptographic digests: each trading reliability for speed differently.

6 stops ~12 min
Prerequisites: Comfort reading Python loops and integer arithmetic, Basic familiarity with bitwise operations (AND, OR, XOR, shift), No prior knowledge of hash function internals required
category-tourhashespythonalgorithmstheAlgorithms

Data Structures in TheAlgorithms/Python

beginner

Seven fundamental data structures side by side: the pointer chain, the key-ordered tree, the self-balancing tree, the heap, the hash table, the union-find, and the prefix tree.

7 stops ~16 min
Prerequisites: Comfort reading Python classes and instance attributes, Familiarity with the concept of pointers or references, No prior knowledge of any specific data structure required
category-tourdata-structurespythonalgorithmstheAlgorithms

Conversion Algorithms in TheAlgorithms/Python

beginner

Seven base, numeral, and unit conversions showing how repeated division, recursion, lookup tables, and pivot factors each solve the same family of problems.

7 stops ~14 min
Prerequisites: Familiarity with Python integers, strings, and list operations, Basic understanding of positional notation (decimal and binary), No prior knowledge of any specific numeral system required
category-tourconversionspythonalgorithmstheAlgorithms

Bit Manipulation in TheAlgorithms/Python

beginner

Seven techniques that use bitwise operations to count, test, flip, reverse, and encode integers without arithmetic.

7 stops ~14 min
Prerequisites: Familiarity with binary (base-2) integer representation, Basic Python: loops, lists, integers, Understanding of bitwise operators: &, |, ^, ~, <<, >>
category-tourbit-manipulationpythonalgorithmstheAlgorithms

String Algorithms in TheAlgorithms/Python

intermediate

Seven string search and comparison algorithms from KMP failure arrays to Aho-Corasick automata.

7 stops ~14 min
Prerequisites: Familiarity with Python strings and list indexing, Basic understanding of hashing and modular arithmetic, Comfort with nested loops and index arithmetic
category-tourstringspythonalgorithmstheAlgorithms

Maths Algorithms in TheAlgorithms/Python

intermediate

Seven mathematical algorithms from prime sieves to the Chinese Remainder Theorem.

7 stops ~14 min
Prerequisites: Basic number theory: primes, divisibility, modular arithmetic, Familiarity with Python type hints and doctest format, Comfort with recursion and bitwise operators
category-tourmathspythonalgorithmstheAlgorithms

Geometry Algorithms in TheAlgorithms/Python

intermediate

Four stops from primitive shapes to convex hull algorithms, with cross-product orientation as the shared computational primitive.

4 stops ~10 min
Prerequisites: Basic understanding of 2D Cartesian coordinates, Familiarity with Python dataclasses and class methods, Knowledge of what a convex hull is conceptually
category-tourgeometrypythonalgorithmstheAlgorithms

Matrix Algorithms in TheAlgorithms/Python

intermediate

Six matrix operations from elementwise addition to Pascal's triangle generation.

6 stops ~12 min
Prerequisites: Familiarity with Python list comprehensions and zip, Basic understanding of matrix concepts: rows, columns, transpose, Comfort with recursion and index arithmetic
category-tourmatrixpythonalgorithmstheAlgorithms

Graph Algorithms in TheAlgorithms/Python

intermediate

Seven graph traversal and shortest-path strategies from BFS queues to Prim's greedy expansion.

7 stops ~14 min
Prerequisites: Familiarity with Python classes and dictionaries, Basic understanding of graph terminology: vertex, edge, adjacency, Comfort with O(n log n) complexity notation
category-tourgraphspythonalgorithmstheAlgorithms

Backtracking Algorithms in TheAlgorithms/Python

intermediate

Seven constraint-satisfaction problems solved by the same pattern: try a placement, recurse, and undo it when the branch fails.

7 stops ~14 min
Prerequisites: Comfort reading recursive Python functions and 2D list indexing, Understanding of what a constraint-satisfaction problem is
category-tourbacktrackingpythonalgorithmstheAlgorithms

Greedy Algorithms in TheAlgorithms/Python

intermediate

Five problems where the locally optimal choice at each step produces the globally optimal result.

5 stops ~11 min
Prerequisites: Understanding of what a sorted list and a greedy choice property mean, Familiarity with basic Python list operations and comprehensions
category-tourgreedy-methodspythonalgorithmstheAlgorithms

Divide and Conquer Algorithms in TheAlgorithms/Python

intermediate

Six algorithms that split a problem in half, solve each half independently, and combine the results: from sorting to matrix multiplication to geometry.

6 stops ~12 min
Prerequisites: Comfort reading recursive Python functions with list slicing, Understanding of what O(n log n) complexity means in terms of recursion depth
category-tourdivide-and-conquerpythonalgorithmstheAlgorithms

Dynamic Programming in TheAlgorithms/Python

intermediate

Seven DP patterns from memoized sequences to all-pairs shortest paths.

7 stops ~14 min
Prerequisites: Familiarity with Python classes and list comprehensions, Basic understanding of recursion and memoization concepts, Comfort reading nested for-loops and 2D array indexing
category-tourdppythonalgorithmstheAlgorithms

Linear Algebra Algorithms in TheAlgorithms/Python

intermediate

Seven direct solvers and iterative methods, from Gaussian elimination to conjugate gradient, each exposing a different trade-off in numerical linear algebra.

7 stops ~14 min
Prerequisites: Familiarity with matrix multiplication and the concept of a system of linear equations, Basic NumPy: arrays, np.dot, np.zeros, np.shape, Understanding of what an eigenvalue and eigenvector are conceptually
category-tourlinear-algebrapythonalgorithmstheAlgorithms

Machine Learning Algorithms in TheAlgorithms/Python

intermediate

Seven classical ML algorithms from linear models to kernel machines, each implemented from scratch in plain NumPy.

7 stops ~14 min
Prerequisites: Familiarity with NumPy arrays and basic linear algebra (dot products, matrix transpose), Understanding of what a training set and a loss function are, No prior knowledge of any specific ML algorithm required
category-tourmachine-learningpythonalgorithmstheAlgorithms

Neural Networks in TheAlgorithms/Python

intermediate

Five files tracing how a network learns: from a single-neuron forward pass to backpropagation, multi-layer weight matrices, and the activation functions that make it possible.

5 stops ~12 min
Prerequisites: Comfort with NumPy matrix operations and Python classes, Basic understanding of what a loss function and a learning rate are
category-tourneural-networkpythonalgorithmstheAlgorithms

Project Euler Solutions in TheAlgorithms/Python

intermediate

The first seven Project Euler problems, each solved in a single Python function with doctests, showing how mathematical insight reduces brute force to a handful of lines.

7 stops ~14 min
Prerequisites: Familiarity with Python generators, loops, and basic math functions, Understanding of what a prime number is, No prior knowledge of any Euler problem required
category-tourproject-eulerpythonalgorithmstheAlgorithms
Your codebase next

Create code tours for your project

Intraview lets AI create interactive walkthroughs of any codebase. Install the free VS Code extension and generate your first tour in minutes.

Install Intraview Free