Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

algorithms

> 编程语言
Open source

Minimal examples of data structures and algorithms in Python

25.5K stars0 likes4 views
WebsiteGitHub

About

Minimal examples of data structures and algorithms in Python

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

bash
pip install algorithms

Use

python
from algorithms.sorting import merge_sort

print(merge_sort([38, 27, 43, 3, 9, 82, 10]))
# [3, 9, 10, 27, 38, 43, 82]
python
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:

python
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:

python
from algorithms.dynamic_programming import count

# Number of ways to make amount 10 using denominations [2, 5, 3, 6]
print(count([2, 5, 3, 6], 10))
# 5

Backtracking — generate permutations:

python
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:

python
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:

python
from algorithms.searching import binary_search

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

Tree — inorder traversal:

python
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:

python
from algorithms.string import knuth_morris_pratt

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

Run Tests

bash
python -m pytest tests/

Project Structure

…

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
vEB Tree veb_tree.py VEBTree

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

  • add_operators — insert +, -, * between digits to reach a target
  • anagram — check if two strings are anagrams
  • array_sum_combinations — find three-element combos from arrays that hit a target sum
  • combination_sum — find combinations (with reuse) that sum to a target
  • factor_combinations — generate all factor combinations of a number
  • find_words — find words on a letter board via trie-based search
  • generate_abbreviations — generate all possible abbreviations of a word
  • generate_parenthesis — generate all valid parenthesis combinations
  • letter_combination — phone keypad digit-to-letter combinations
  • palindrome_partitioning — partition a string into palindromic substrings
  • pattern_match — match a string to a pattern via bijection mapping
  • permute — generate all permutations of distinct elements
  • permute_unique — generate unique permutations when duplicates exist
  • subsets — generate all subsets (power set)
  • minimax — game-tree search with alpha-beta pruning
  • subsets_unique — generate unique subsets when duplicates exist

Bit Manipulation

  • add_bitwise_operator — add two integers using only bitwise operations
  • binary_gap — longest distance between consecutive 1-bits
  • bit_operation — get, set, clear, and update individual bits
  • bytes_int_conversion — convert between integers and byte sequences
  • count_flips_to_convert — count bit flips needed to convert one integer to another
  • count_ones — count the number of 1-bits (Hamming weight)
  • find_difference — find the added character between two strings using XOR
  • find_missing_number — find a missing number in a sequence using XOR
  • flip_bit_longest_sequence — longest run of 1s after flipping a single 0
  • gray_code — generate Gray code sequences and convert between Gray and binary
  • has_alternative_bit — check if binary representation has alternating bits
  • insert_bit — insert bits at a specific position in an integer
  • power_of_two — check if an integer is a power of two
  • remove_bit — remove a bit at a given position
  • reverse_bits — reverse all 32 bits of an unsigned integer
  • single_number — find the element appearing once (others appear twice) via XOR
  • single_number2 — find the element appearing once (others appear three times)
  • single_number3 — find two unique elements (others appear twice)
  • subsets — generate all subsets using bitmask enumeration
  • swap_pair — swap adjacent bit pairs in an integer

Compression

  • elias — Elias gamma and delta universal integer coding
  • huffman_coding — variable-length prefix codes for lossless compression
  • lzw_compression — dictionary-based Lempel-Ziv-Welch 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](algorithms/dynamic_pro

Issues· 14 open

View all issuesOpen on GitHub
  • #2771

    longest_palindrome drops # characters from the result

    Updated Sep 17, 2026
  • #2766

    You're on the SigRank board — claim your profile or remove it

    Updated Jul 14, 2026
  • #2747

    Name of file does not match with the algorithm implemented in that file.

    Updated May 26, 2026

> Tags

Pythonalgorithmalgorithmscompetitive-programmingdata-structure

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 30, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言