MCPcopy
hub / github.com/keon/algorithms

github.com/keon/algorithms @v1.0.1 sqlite

repository ↗ · DeepWiki ↗ · release v1.0.1 ↗
1,833 symbols 4,986 edges 426 files 929 documented · 51%
README

PyPI version Open Source Helpers

algorithms

Minimal, clean, and well-documented implementations of data structures and algorithms in Python 3.

Each file is self-contained with docstrings, type hints, and complexity notes — designed to be read and learned from.

Quick Start

Install

pip install algorithms

Use

from algorithms.sorting import merge_sort

print(merge_sort([38, 27, 43, 3, 9, 82, 10]))
# [3, 9, 10, 27, 38, 43, 82]
from algorithms.data_structures import BinaryHeap, Trie, BST
from algorithms.graph import dijkstra, bellman_ford
from algorithms.tree import TreeNode

Examples

Graph — Dijkstra's shortest path:

from algorithms.graph import dijkstra

graph = {
    "s": {"a": 2, "b": 1},
    "a": {"s": 3, "b": 4, "c": 8},
    "b": {"s": 4, "a": 2, "d": 2},
    "c": {"a": 2, "d": 7, "t": 4},
    "d": {"b": 1, "c": 11, "t": 5},
    "t": {"c": 3, "d": 5},
}
print(dijkstra(graph, "s", "t"))
# (8, ['s', 'b', 'd', 't'])

Dynamic programming — coin change:

from algorithms.dynamic_programming import coin_change

# Minimum coins to make amount 29 using denominations [1, 5, 10, 25]
print(coin_change([1, 5, 10, 25], 29))
# 7   (25 + 1 + 1 + 1 + 1)

Backtracking — generate permutations:

from algorithms.backtracking import permute

print(permute([1, 2, 3]))
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

Data structures — binary heap:

from algorithms.data_structures import BinaryHeap

heap = BinaryHeap()
for val in [5, 3, 8, 1, 9]:
    heap.insert(val)
print(heap.remove_min())  # 1
print(heap.remove_min())  # 3

Searching — binary search:

from algorithms.searching import binary_search

print(binary_search([1, 3, 5, 7, 9, 11], 7))
# 3   (index of target)

Tree — inorder traversal:

from algorithms.tree import TreeNode
from algorithms.tree import inorder

root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(6)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)

print(inorder(root))
# [1, 2, 3, 4, 6]

String — Knuth-Morris-Pratt pattern matching:

from algorithms.string import knuth_morris_pratt

print(knuth_morris_pratt("abxabcabcaby", "abcaby"))
# 6   (starting index of match)

Run Tests

python -m pytest tests/

Project Structure

algorithms/
    data_structures/     # Reusable data structure implementations
    array/               # Array manipulation algorithms
    backtracking/        # Constraint satisfaction & enumeration
    bit_manipulation/    # Bitwise operations & tricks
    compression/         # Encoding & compression schemes
    dynamic_programming/ # Optimal substructure & memoization
    graph/               # Graph algorithms (BFS, DFS, shortest path, flow, ...)
    greedy/              # Greedy strategies
    heap/                # Heap-based algorithms
    linked_list/         # Linked list algorithms
    map/                 # Hash-map-based algorithms
    math/                # Number theory, combinatorics, algebra
    matrix/              # 2D array & linear algebra operations
    queue/               # Queue-based algorithms
    searching/           # Search algorithms (binary, linear, ...)
    set/                 # Set-based algorithms
    sorting/             # Sorting algorithms
    stack/               # Stack-based algorithms
    streaming/           # Streaming & sketching algorithms
    string/              # String matching, manipulation, parsing
    tree/                # Tree algorithms (traversal, BST ops, ...)
tests/                   # One test file per topic

Data Structures

All core data structures live in algorithms/data_structures/:

Data Structure Module Key Classes
AVL Tree avl_tree.py AvlTree
B-Tree b_tree.py BTree
Binary Search Tree bst.py BST
Fenwick Tree fenwick_tree.py Fenwick_Tree
Graph graph.py Node, DirectedEdge, DirectedGraph
Hash Table hash_table.py HashTable, ResizableHashTable
Heap heap.py BinaryHeap
KD Tree kd_tree.py KDTree
Linked List linked_list.py SinglyLinkedListNode, DoublyLinkedListNode
Priority Queue priority_queue.py PriorityQueue
Queue queue.py ArrayQueue, LinkedListQueue
Red-Black Tree red_black_tree.py RBTree
Segment Tree segment_tree.py, iterative_segment_tree.py SegmentTree
Separate Chaining Hash Table separate_chaining_hash_table.py SeparateChainingHashTable
Sqrt Decomposition sqrt_decomposition.py SqrtDecomposition
Stack stack.py ArrayStack, LinkedListStack
Trie trie.py Trie
Union-Find union_find.py Union

Algorithms

Array

  • delete_nth — keep at most N occurrences of each element
  • flatten — recursively flatten nested arrays into a single list
  • garage — minimum swaps to rearrange a parking lot
  • josephus — eliminate every k-th person in a circular arrangement
  • limit — filter elements within min/max bounds
  • longest_non_repeat — longest substring without repeating characters
  • max_ones_index — find the zero to flip for the longest run of ones
  • merge_intervals — combine overlapping intervals
  • missing_ranges — find gaps between a low and high bound
  • move_zeros — move all zeros to the end, preserving order
  • n_sum — find all unique n-tuples that sum to a target
  • plus_one — add one to a number represented as a digit array
  • remove_duplicates — remove duplicate elements preserving order
  • rotate — rotate an array right by k positions
  • summarize_ranges — summarize consecutive integers as range tuples
  • three_sum — find all unique triplets that sum to zero
  • top_1 — find the most frequently occurring values
  • trimmean — compute mean after trimming extreme values
  • two_sum — find two indices whose values sum to a target

Backtracking

Bit Manipulation

Compression

  • elias — Elias gamma and delta universal integer coding
  • huffman_coding — variable-length prefix codes for lossless compression
  • rle_compression — run-length encoding for consecutive character compression

Dynamic Programming

  • bitmask — travelling salesman problem via bitmask dynamic programming
  • buy_sell_stock — maximize profit from a stock price array
  • climbing_stairs — count ways to climb stairs taking 1 or 2 steps
  • coin_change — minimum coins to make a given amount
  • combination_sum — count combinations that sum to a target (with reuse)
  • count_paths_dp — count paths in a grid using recursion, memoization, and bottom-up DP
  • edit_distance — minimum edits to transform one string into another
  • egg_drop — minimize trials to find the critical floor
  • fibonacci — compute Fibonacci numbers with memoization
  • hosoya_triangle — generate the Hosoya triangle of Fibonacci-like numbers
  • house_robber — maximize loot from non-adjacent houses
  • int_divide — count the number of integer partitions
  • job_scheduling — maximize profit from weighted job scheduling
  • k_factor — find the k-factor of a string pattern
  • knapsack — maximize value under a weight constraint
  • longest_common_subsequence — find the longest common subsequence of two strings
  • longest_increasing — find the longest increasing subsequence
  • matrix_chain_order — minimize scalar multiplications for matrix chain
  • [max_product_subar

Core symbols most depended-on inside this repo

pop
called by 86
algorithms/stack/ordered_stack.py
insert
called by 62
algorithms/data_structures/bst.py
get
called by 48
algorithms/data_structures/hash_table.py
put
called by 25
algorithms/data_structures/hash_table.py
add
called by 24
algorithms/data_structures/union_find.py
clone
called by 24
algorithms/math/polynomial.py
_rationalize_if_possible
called by 22
algorithms/math/polynomial.py
all_monomials
called by 19
algorithms/math/polynomial.py

Shape

Method 907
Function 609
Class 317

Languages

Python100%

Modules by API surface

tests/test_string.py112 symbols
tests/test_community_algorithms.py85 symbols
tests/test_math.py79 symbols
tests/test_graph.py66 symbols
tests/test_dynamic_programming.py49 symbols
tests/test_array.py48 symbols
tests/test_backtracking.py41 symbols
tests/test_issue_fixes.py38 symbols
algorithms/compression/huffman_coding.py38 symbols
algorithms/math/polynomial.py32 symbols
tests/test_map.py31 symbols
tests/test_bit_manipulation.py31 symbols

For agents

$ claude mcp add algorithms \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact