Convert Figma logo to code with AI

keon logoalgorithms

Minimal examples of data structures and algorithms in Python

25,500
4,719
25,500
3

Top Related Projects

221,884

All Algorithms implemented in Python

Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards.

📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings

Demonstrate all the questions on LeetCode in the form of animation.(用动画的形式呈现解LeetCode题目的思路,完整单步/回看/变速/语音讲解在 algomooc.com)

55,772

LeetCode Solutions: A Record of My Problem Solving Journey.( leetcode题解,记录自己的leetcode解题之路。)

🌍 针对小白的算法训练 | 包括四部分:①.大厂面经 ②.力扣图解 ③.千本开源电子书 ④.百张技术思维导图(项目花了上百小时,希望可以点 star 支持,🌹感谢~)推荐免费ChatGPT使用网站

Quick Overview

The keon/algorithms repository is a comprehensive collection of algorithms and data structures implemented in Python. It serves as an educational resource for computer science students, developers, and anyone interested in learning about various algorithmic concepts and their implementations.

Pros

  • Extensive coverage of algorithms and data structures
  • Well-organized and categorized implementations
  • Clear and readable Python code
  • Includes unit tests for most implementations

Cons

  • Some implementations may not be optimized for performance
  • Limited documentation for some algorithms
  • Not actively maintained (last commit over a year ago)
  • Lacks advanced or specialized algorithms in certain areas

Code Examples

  1. Binary Search implementation:
def binary_search(array, target):
    left, right = 0, len(array) - 1
    while left <= right:
        mid = (left + right) // 2
        if array[mid] == target:
            return mid
        elif array[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

This code implements the binary search algorithm, which efficiently finds a target value in a sorted array.

  1. Bubble Sort implementation:
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

This code implements the bubble sort algorithm, which sorts an array by repeatedly swapping adjacent elements if they are in the wrong order.

  1. Depth-First Search (DFS) implementation:
def dfs(graph, start, visited=None):
    if visited is None:
        visited = set()
    visited.add(start)
    print(start)
    for next in graph[start] - visited:
        dfs(graph, next, visited)
    return visited

This code implements the depth-first search algorithm for traversing or searching tree or graph data structures.

Getting Started

To use the algorithms in this repository:

  1. Clone the repository:

    git clone https://github.com/keon/algorithms.git
    
  2. Navigate to the desired algorithm's directory:

    cd algorithms/algorithms/sort
    
  3. Import and use the algorithm in your Python code:

    from bubble_sort import bubble_sort
    
    arr = [64, 34, 25, 12, 22, 11, 90]
    sorted_arr = bubble_sort(arr)
    print(sorted_arr)
    

This will import and use the bubble sort algorithm from the repository.

Competitor Comparisons

221,884

All Algorithms implemented in Python

Pros of TheAlgorithms/Python

  • Larger collection of algorithms and data structures
  • More active community with frequent updates and contributions
  • Better organization with categorized folders for different algorithm types

Cons of TheAlgorithms/Python

  • Less focus on optimization and efficiency in some implementations
  • May be overwhelming for beginners due to the vast number of algorithms

Code Comparison

algorithms implementation of binary search:

def binary_search(list, item):
    low = 0
    high = len(list) - 1
    while low <= high:
        mid = (low + high) // 2
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None

TheAlgorithms/Python implementation of binary search:

def binary_search(array, target):
    left, right = 0, len(array) - 1
    while left <= right:
        mid = (left + right) // 2
        if array[mid] == target:
            return mid
        elif array[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

Both implementations are similar in approach, with minor differences in variable naming and return values for unsuccessful searches.

Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards.

Pros of system-design-primer

  • Comprehensive coverage of system design concepts and best practices
  • Includes real-world examples and case studies from large-scale systems
  • Provides interactive learning resources like quizzes and exercises

Cons of system-design-primer

  • Focuses primarily on high-level system design, less on implementation details
  • May be overwhelming for beginners due to its extensive content
  • Requires more time investment to fully grasp all concepts

Code comparison

system-design-primer doesn't typically include code snippets, as it focuses on high-level design concepts. In contrast, algorithms provides implementation examples:

# Example from algorithms
def bubble_sort(collection):
    length = len(collection)
    for i in range(length - 1):
        for j in range(length - 1 - i):
            if collection[j] > collection[j + 1]:
                collection[j], collection[j + 1] = collection[j + 1], collection[j]
    return collection

algorithms offers practical implementations of various algorithms and data structures, making it more suitable for those looking to improve their coding skills and understand algorithm implementation details. system-design-primer, on the other hand, is better suited for developers preparing for system design interviews or looking to understand large-scale system architecture concepts.

📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings

Pros of javascript-algorithms

  • Focused specifically on JavaScript implementations
  • More comprehensive coverage of algorithms and data structures
  • Includes explanations and complexity analysis for each algorithm

Cons of javascript-algorithms

  • Larger repository size, potentially overwhelming for beginners
  • Less language diversity compared to algorithms

Code Comparison

algorithms (Python):

def binary_search(list, item):
    low = 0
    high = len(list) - 1
    while low <= high:
        mid = (low + high) // 2
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None

javascript-algorithms (JavaScript):

function binarySearch(sortedArray, seekElement) {
  let startIndex = 0;
  let endIndex = sortedArray.length - 1;
  while (startIndex <= endIndex) {
    const middleIndex = startIndex + Math.floor((endIndex - startIndex) / 2);
    if (sortedArray[middleIndex] === seekElement) {
      return middleIndex;
    }
    if (sortedArray[middleIndex] < seekElement) {
      startIndex = middleIndex + 1;
    } else {
      endIndex = middleIndex - 1;
    }
  }
  return -1;
}

Both repositories offer valuable resources for learning algorithms and data structures. algorithms provides implementations in multiple languages, making it versatile for different programming backgrounds. javascript-algorithms offers a more in-depth focus on JavaScript, with detailed explanations and analysis. The choice between them depends on the user's specific language needs and depth of study desired.

Demonstrate all the questions on LeetCode in the form of animation.(用动画的形式呈现解LeetCode题目的思路,完整单步/回看/变速/语音讲解在 algomooc.com)

Pros of LeetCodeAnimation

  • Provides animated visualizations of algorithms, making them easier to understand
  • Focuses specifically on LeetCode problems, which is beneficial for interview preparation
  • Includes explanations in Chinese, catering to a wider audience

Cons of LeetCodeAnimation

  • Limited to a smaller set of algorithms compared to algorithms
  • Animations may not be as helpful for experienced programmers who prefer text-based explanations
  • Less comprehensive coverage of general algorithmic concepts

Code Comparison

algorithms:

def binary_search(list, item):
    low = 0
    high = len(list) - 1
    while low <= high:
        mid = (low + high) // 2
        guess = list[mid]
        if guess == item:
            return mid

LeetCodeAnimation:

public int search(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) return mid;
        if (target < nums[mid]) right = mid - 1;

Both repositories provide implementations of binary search, but algorithms uses Python while LeetCodeAnimation uses Java. The algorithms implementation is more concise, while LeetCodeAnimation's version includes additional logic for handling different cases.

55,772

LeetCode Solutions: A Record of My Problem Solving Journey.( leetcode题解,记录自己的leetcode解题之路。)

Pros of leetcode

  • More comprehensive coverage of LeetCode problems
  • Solutions in multiple programming languages (JavaScript, Python, Java, etc.)
  • Detailed explanations and analysis for each problem

Cons of leetcode

  • Less focus on general algorithms and data structures
  • May be overwhelming for beginners due to the large number of problems

Code Comparison

leetcode (JavaScript):

var twoSum = function(nums, target) {
    const map = new Map();
    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i];
        if (map.has(complement)) {
            return [map.get(complement), i];
        }
        map.set(nums[i], i);
    }
};

algorithms (Python):

def two_sum(nums, target):
    dic = {}
    for i, num in enumerate(nums):
        if num in dic:
            return [dic[num], i]
        else:
            dic[target - num] = i

Both repositories provide solutions to the "Two Sum" problem, but leetcode offers implementations in multiple languages, while algorithms focuses on Python. The leetcode solution includes more detailed comments and explanations in the full repository.

🌍 针对小白的算法训练 | 包括四部分:①.大厂面经 ②.力扣图解 ③.千本开源电子书 ④.百张技术思维导图(项目花了上百小时,希望可以点 star 支持,🌹感谢~)推荐免费ChatGPT使用网站

Pros of hello-algorithm

  • Extensive collection of algorithms and data structures in multiple programming languages
  • Includes visual explanations and diagrams for better understanding
  • Offers additional resources like interview preparation materials

Cons of hello-algorithm

  • Less organized structure compared to algorithms
  • May be overwhelming for beginners due to the large amount of content
  • Some explanations are in Chinese, which may be a barrier for non-Chinese speakers

Code Comparison

algorithms (Python):

def binary_search(list, item):
    low = 0
    high = len(list) - 1
    while low <= high:
        mid = (low + high) // 2
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None

hello-algorithm (Java):

public static int binarySearch(int[] arr, int target) {
    int left = 0, right = arr.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] == target) return mid;
        if (arr[mid] < target) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}

Both repositories provide implementations of common algorithms, but hello-algorithm offers a wider range of languages and more comprehensive explanations. However, algorithms has a more structured and beginner-friendly approach, making it easier to navigate and learn from.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

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

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 StructureModuleKey Classes
AVL Treeavl_tree.pyAvlTree
B-Treeb_tree.pyBTree
Binary Search Treebst.pyBST
Fenwick Treefenwick_tree.pyFenwick_Tree
Graphgraph.pyNode, DirectedEdge, DirectedGraph
Hash Tablehash_table.pyHashTable, ResizableHashTable
Heapheap.pyBinaryHeap
KD Treekd_tree.pyKDTree
Linked Listlinked_list.pySinglyLinkedListNode, DoublyLinkedListNode
Priority Queuepriority_queue.pyPriorityQueue
Queuequeue.pyArrayQueue, LinkedListQueue
Red-Black Treered_black_tree.pyRBTree
Segment Treesegment_tree.py, iterative_segment_tree.pySegmentTree
Separate Chaining Hash Tableseparate_chaining_hash_table.pySeparateChainingHashTable
Sqrt Decompositionsqrt_decomposition.pySqrtDecomposition
Stackstack.pyArrayStack, LinkedListStack
Trietrie.pyTrie
Union-Findunion_find.pyUnion
vEB Treeveb_tree.pyVEBTree

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

Graph

Greedy

Heap

Linked List

Map

Math

Matrix

Queue

Searching

Set

Sorting

  • bead_sort — gravity-based natural sorting (bead/abacus sort)
  • bitonic_sort — parallel-friendly comparison sort via bitonic sequences
  • bogo_sort — random permutation sort (intentionally inefficient)
  • bubble_sort — repeatedly swap adjacent out-of-order elements
  • bucket_sort — distribute elements into buckets, then sort each
  • cocktail_shaker_sort — bidirectional bubble sort
  • comb_sort — bubble sort improved with a shrinking gap
  • counting_sort — sort integers by counting occurrences
  • cycle_sort — in-place sort that minimizes total writes
  • exchange_sort — simple pairwise comparison and exchange
  • gnome_sort — sort by swapping elements backward until ordered
  • heap_sort — sort via a binary heap (in-place, O(n log n))
  • insertion_sort — build a sorted portion one element at a time
  • meeting_rooms — determine if meeting intervals overlap
  • merge_sort — divide-and-conquer stable sort (O(n log n))
  • pancake_sort — sort using only prefix reversals
  • pigeonhole_sort — sort by placing elements into pigeonhole buckets
  • quick_sort — partition-based divide-and-conquer sort
  • radix_sort — non-comparative sort processing one digit at a time
  • selection_sort — repeatedly select the minimum and swap it forward
  • shell_sort — generalized insertion sort with a decreasing gap sequence
  • sort_colors — Dutch national flag three-way partition
  • stooge_sort — recursive sort by dividing into overlapping thirds
  • wiggle_sort — rearrange into an alternating peak-valley pattern

Stack

Streaming

String

Tree

Contributing

Thanks for your interest in contributing! There are many ways to get involved. See CONTRIBUTING.md for details.

Maintainers

Contributors

Thanks to all the contributors who helped build this repo.

License

MIT