instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings for production code
from __future__ import annotations def find_missing_number(nums: list[int]) -> int: missing = 0 for index, number in enumerate(nums): missing ^= number missing ^= index + 1 return missing def find_missing_number2(nums: list[int]) -> int: total = sum(nums) length = len(nums) ...
--- +++ @@ -1,8 +1,38 @@+""" +Find Missing Number + +Given a sequence of unique integers in the range [0..n] with one value +missing, find and return that missing number. Two approaches are provided: +XOR-based and summation-based. + +Reference: https://en.wikipedia.org/wiki/Exclusive_or + +Complexity: + Time: O(n)...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/find_missing_number.py
Replace inline comments with docstrings
from __future__ import annotations import itertools from functools import partial def array_sum_combinations( array_a: list[int], array_b: list[int], array_c: list[int], target: int, ) -> list[list[int]]: arrays = [array_a, array_b, array_c] def _is_complete(constructed_so_far: list[int]) -...
--- +++ @@ -1,3 +1,15 @@+""" +Array Sum Combinations + +Given three arrays and a target sum, find all three-element combinations +(one element from each array) that add up to the target. + +Reference: https://en.wikipedia.org/wiki/Subset_sum_problem + +Complexity: + Time: O(n^3) brute-force product of three arrays ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/array_sum_combinations.py
Document my Python code with docstrings
from __future__ import annotations from collections import deque def int_to_bytes_big_endian(number: int) -> bytes: byte_buffer: deque[int] = deque() while number > 0: byte_buffer.appendleft(number & 0xFF) number >>= 8 return bytes(byte_buffer) def int_to_bytes_little_endian(number: in...
--- +++ @@ -1,3 +1,15 @@+""" +Bytes-Integer Conversion + +Convert between Python integers and raw byte sequences in both big-endian +and little-endian byte orders. + +Reference: https://en.wikipedia.org/wiki/Endianness + +Complexity: + Time: O(b) where b is the number of bytes in the representation + Space: O(b)...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/bytes_int_conversion.py
Write reusable docstrings
from __future__ import annotations from typing import Any def top_1(array: list[Any]) -> list[Any]: frequency = {} for element in array: if element in frequency: frequency[element] += 1 else: frequency[element] = 1 max_count = max(frequency.values()) result ...
--- +++ @@ -1,3 +1,15 @@+""" +Top 1 (Mode) + +Find the most frequently occurring value(s) in an array. When multiple +values share the highest frequency, all are returned. + +Reference: https://en.wikipedia.org/wiki/Mode_(statistics) + +Complexity: + Time: O(n) + Space: O(n) +""" from __future__ import annota...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/array/top_1.py
Create Google-style docstrings for my code
from __future__ import annotations class Node: def __init__(self) -> None: self.keys: list = [] self.children: list[Node] = [] def __repr__(self) -> str: return f"<id_node: {self.keys}>" @property def is_leaf(self) -> bool: return len(self.children) == 0 class BTr...
--- +++ @@ -1,22 +1,63 @@+""" +B-Tree + +A self-balancing tree data structure optimized for disk operations. Each node +(except root) contains at least t-1 keys and at most 2t-1 keys, where t is the +minimum degree. The tree grows upward from the root. + +Reference: https://en.wikipedia.org/wiki/B-tree + +Complexity: +...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/b_tree.py
Replace inline comments with docstrings
from __future__ import annotations from collections.abc import Generator def permute(elements: list | str) -> list: if len(elements) <= 1: return [elements] result = [] for perm in permute(elements[1:]): for i in range(len(elements)): result.append(perm[:i] + elements[0:1] + ...
--- +++ @@ -1,3 +1,14 @@+""" +Permutations + +Given a collection of distinct elements, return all possible permutations. + +Reference: https://en.wikipedia.org/wiki/Permutation + +Complexity: + Time: O(n * n!) where n is the number of elements + Space: O(n * n!) to store all permutations +""" from __future__ ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/permute.py
Write docstrings for backend logic
from __future__ import annotations def encode_rle(data: str) -> str: if not data: return "" encoded: str = "" prev_char: str = "" count: int = 1 for char in data: if char != prev_char: if prev_char: encoded += str(count) + prev_char count ...
--- +++ @@ -1,8 +1,35 @@+""" +Run-Length Encoding (RLE) + +A simple lossless compression algorithm that encodes consecutive repeated +characters as a count followed by the character. Decompression fully recovers +the original data. + +Reference: https://en.wikipedia.org/wiki/Run-length_encoding + +Complexity: + Time...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/compression/rle_compression.py
Document all public functions with docstrings
from __future__ import annotations def generate_parenthesis_v1(count: int) -> list[str]: result: list[str] = [] _add_pair_v1(result, "", count, 0) return result def _add_pair_v1( result: list[str], current: str, left: int, right: int, ) -> None: if left == 0 and right == 0: ...
--- +++ @@ -1,8 +1,35 @@+""" +Generate Parentheses + +Given n pairs of parentheses, generate all combinations of well-formed +parentheses. + +Reference: https://leetcode.com/problems/generate-parentheses/ + +Complexity: + Time: O(4^n / sqrt(n)) — the n-th Catalan number + Space: O(n) recursion depth +""" from...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/generate_parenthesis.py
Improve documentation using docstrings
from __future__ import annotations def permute_unique(nums: list[int]) -> list[list[int]]: permutations: list[list[int]] = [[]] for number in nums: new_permutations: list[list[int]] = [] for existing in permutations: for i in range(len(existing) + 1): new_permutati...
--- +++ @@ -1,8 +1,32 @@+""" +Unique Permutations + +Given a collection of numbers that might contain duplicates, return all +possible unique permutations. + +Reference: https://leetcode.com/problems/permutations-ii/ + +Complexity: + Time: O(n * n!) worst case + Space: O(n * n!) to store all unique permutations ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/permute_unique.py
Add docstrings to clarify complex logic
from __future__ import annotations from abc import ABCMeta, abstractmethod class AbstractHeap(metaclass=ABCMeta): def __init__(self) -> None: # noqa: B027 @abstractmethod def perc_up(self, index: int) -> None: @abstractmethod def insert(self, val: int) -> None: @abstractmethod def p...
--- +++ @@ -1,3 +1,16 @@+r""" +Binary Heap + +A min heap is a complete binary tree where each node is smaller than +its children. The root is the minimum element. Uses an array +representation with index 0 as a sentinel. + +Reference: https://en.wikipedia.org/wiki/Binary_heap + +Complexity: + Time: O(log n) for ins...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/heap.py
Generate descriptive docstrings automatically
from __future__ import annotations def generate_abbreviations(word: str) -> list[str]: result: list[str] = [] _backtrack(result, word, 0, 0, "") return result def _backtrack( result: list[str], word: str, position: int, count: int, current: str, ) -> None: if position == len(wor...
--- +++ @@ -1,8 +1,32 @@+""" +Generalized Abbreviations + +Given a word, return all possible generalized abbreviations. Each +abbreviation replaces contiguous substrings with their lengths. + +Reference: https://leetcode.com/problems/generalized-abbreviation/ + +Complexity: + Time: O(2^n) where n is the length of t...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/generate_abbreviations.py
Add docstrings for utility scripts
from __future__ import annotations class HashTable: _empty = object() _deleted = object() def __init__(self, size: int = 11) -> None: self.size = size self._len = 0 self._keys: list[object] = [self._empty] * size self._values: list[object] = [self._empty] * size def...
--- +++ @@ -1,19 +1,54 @@+""" +Hash Table (Open Addressing) + +Hash map implementation using open addressing with linear probing +for collision resolution. Includes a resizable variant that doubles +capacity when the load factor reaches two-thirds. + +Reference: https://en.wikipedia.org/wiki/Open_addressing + +Complexi...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/hash_table.py
Write docstrings including parameters and return values
from __future__ import annotations def find_words(board: list[list[str]], words: list[str]) -> list[str]: trie: dict = {} for word in words: current_node = trie for char in word: if char not in current_node: current_node[char] = {} current_node = curren...
--- +++ @@ -1,8 +1,38 @@+""" +Word Search II + +Given a board of characters and a list of words, find all words that can +be constructed from adjacent cells (horizontally or vertically). Each cell +may only be used once per word. Uses a trie for efficient prefix matching. + +Reference: https://leetcode.com/problems/wor...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/find_words.py
Add structured docstrings to improve clarity
from __future__ import annotations import itertools from collections.abc import Iterable from typing import Any class PriorityQueueNode: def __init__(self, data: Any, priority: Any) -> None: self.data = data self.priority = priority def __repr__(self) -> str: return f"{self.data}: ...
--- +++ @@ -1,3 +1,15 @@+""" +Priority Queue (Linear Array) + +A priority queue implementation using a sorted linear array. Elements +are inserted in order so that extraction of the minimum is O(1). + +Reference: https://en.wikipedia.org/wiki/Priority_queue + +Complexity: + Time: O(n) for push, O(1) for pop + Sp...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/priority_queue.py
Add docstrings including usage examples
from __future__ import annotations import math from typing import Any class KDNode: __slots__ = ("point", "left", "right", "axis") def __init__( self, point: tuple[float, ...], left: KDNode | None = None, right: KDNode | None = None, axis: int = 0, ) -> None: ...
--- +++ @@ -1,3 +1,9 @@+"""KD-tree — a space-partitioning tree for k-dimensional points. + +Supports efficient nearest-neighbour and range queries. + +Inspired by PR #915 (gjones1077). +""" from __future__ import annotations @@ -6,6 +12,7 @@ class KDNode: + """A single node in a KD-tree.""" __slots__...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/kd_tree.py
Turn comments into proper docstrings
from __future__ import annotations class Node: def __init__(self, data: int) -> None: self.data: int = data self.left: Node | None = None self.right: Node | None = None class BST: def __init__(self) -> None: self.root: Node | None = None def get_root(self) -> Node | None...
--- +++ @@ -1,3 +1,17 @@+"""Binary Search Tree implementation. + +A BST is a node-based binary tree where each node's left subtree contains +only nodes with data less than the node's data, and the right subtree +contains only nodes with data greater than the node's data. + +Operations and complexities (n = number of no...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/bst.py
Generate docstrings for each module
from __future__ import annotations def flip_bit_longest_seq(number: int) -> int: current_length = 0 previous_length = 0 max_length = 0 while number: if number & 1 == 1: current_length += 1 elif number & 1 == 0: previous_length = 0 if number & 2 == 0 else curre...
--- +++ @@ -1,8 +1,38 @@+""" +Flip Bit Longest Sequence + +Given an integer, find the length of the longest sequence of 1-bits you +can create by flipping exactly one 0-bit to a 1-bit. + +Reference: https://en.wikipedia.org/wiki/Bit_manipulation + +Complexity: + Time: O(b) where b is the number of bits in the integ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/flip_bit_longest_sequence.py
Write beginner-friendly docstrings
from __future__ import annotations class SinglyLinkedListNode: def __init__(self, value: object) -> None: self.value = value self.next: SinglyLinkedListNode | None = None class DoublyLinkedListNode: def __init__(self, value: object) -> None: self.value = value self.next: D...
--- +++ @@ -1,8 +1,26 @@+""" +Linked List Node Definitions + +Basic node classes for singly and doubly linked lists, serving as foundational +building blocks for linked list algorithms. + +Reference: https://en.wikipedia.org/wiki/Linked_list + +Complexity: + Time: O(1) for node creation + Space: O(1) per node +"...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/linked_list.py
Add documentation for all methods
from __future__ import annotations def get_factors(number: int) -> list[list[int]]: todo: list[tuple[int, int, list[int]]] = [(number, 2, [])] combinations: list[list[int]] = [] while todo: remaining, divisor, partial = todo.pop() while divisor * divisor <= remaining: if remai...
--- +++ @@ -1,8 +1,32 @@+""" +Factor Combinations + +Given an integer n, return all possible combinations of its factors. +Factors should be greater than 1 and less than n. + +Reference: https://leetcode.com/problems/factor-combinations/ + +Complexity: + Time: O(n * log(n)) approximate + Space: O(log(n)) recursi...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/backtracking/factor_combinations.py
Add docstrings that explain logic
from __future__ import annotations from abc import ABCMeta, abstractmethod from collections.abc import Iterator class AbstractStack(metaclass=ABCMeta): def __init__(self) -> None: self._top = -1 def __len__(self) -> int: return self._top + 1 def __str__(self) -> str: result = ...
--- +++ @@ -1,3 +1,15 @@+""" +Stack Abstract Data Type + +Implementations of the stack ADT using both a fixed-size array and a +linked list. Both support push, pop, peek, is_empty, len, iter, and str. + +Reference: https://en.wikipedia.org/wiki/Stack_(abstract_data_type) + +Complexity: + Time: O(1) for push/pop/pee...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/stack.py
Write docstrings describing each step
import math class VEBTree: def __init__(self, universe_size): if not isinstance(universe_size, int): raise TypeError("universe_size must be an integer.") if not universe_size > 0: raise ValueError("universe_size must be greater than 0.") if not (universe_size & (u...
--- +++ @@ -1,10 +1,45 @@+""" +Van Emde Boas Tree (vEB Tree) / van Emde Boas priority queue + +Reference: https://en.wikipedia.org/wiki/Van_Emde_Boas_tree + +A van Emde Boas tree is a recursive data structure for storing integers +from a fixed universe [0, u - 1], where u is a power of 2. + +Time complexity: + inser...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/veb_tree.py
Auto-generate documentation strings for this file
from __future__ import annotations class _Node: def __init__( self, key: object = None, value: object = None, next_node: _Node | None = None, ) -> None: self.key = key self.value = value self.next = next_node class SeparateChainingHashTable: _em...
--- +++ @@ -1,8 +1,27 @@+""" +Separate Chaining Hash Table + +Hash table implementation using separate chaining (linked lists) for +collision resolution. + +Reference: https://en.wikipedia.org/wiki/Hash_table#Separate_chaining + +Complexity: + Time: O(1) average for put/get/del, O(n) worst case + Space: O(n) +""...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/separate_chaining_hash_table.py
Document all public functions with docstrings
from __future__ import annotations from functools import cache def count_paths_recursive(m: int, n: int) -> int: if m == 1 or n == 1: return 1 return count_paths_recursive(m - 1, n) + count_paths_recursive(m, n - 1) def count_paths_memo(m: int, n: int) -> int: @cache def helper(i: int, j:...
--- +++ @@ -1,3 +1,10 @@+"""Count paths in a grid — recursive, memoized, and bottom-up DP. + +Count the number of unique paths from the top-left to the bottom-right +of an m x n grid, moving only right or down. + +Inspired by PR #857 (c-cret). +""" from __future__ import annotations @@ -5,12 +12,14 @@ def coun...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/count_paths_dp.py
Provide clean and structured docstrings
from __future__ import annotations import math class SqrtDecomposition: def __init__(self, arr: list[int | float]) -> None: self.data = list(arr) n = len(self.data) self.block_size = max(1, math.isqrt(n)) num_blocks = (n + self.block_size - 1) // self.block_size self.blo...
--- +++ @@ -1,3 +1,22 @@+""" +Square Root (Sqrt) Decomposition + +Divides an array into blocks of size √n to allow O(√n) range queries and +point updates — a simple alternative to segment trees for range-aggregate +problems. + +Supports: +- **Range sum queries** in O(√n). +- **Point updates** in O(1). + +Reference: htt...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/sqrt_decomposition.py
Add docstrings following best practices
from __future__ import annotations def max_profit_naive(prices: list[int]) -> int: max_so_far = 0 for i in range(0, len(prices) - 1): for j in range(i + 1, len(prices)): max_so_far = max(max_so_far, prices[j] - prices[i]) return max_so_far def max_profit_optimized(prices: list[int])...
--- +++ @@ -1,8 +1,38 @@+""" +Best Time to Buy and Sell Stock + +Given an array of stock prices, find the maximum profit from a single +buy-sell transaction (buy before sell). + +Reference: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ + +Complexity: + max_profit_naive: + Time: O(n^2) + ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/buy_sell_stock.py
Include argument descriptions in docstrings
from __future__ import annotations class Union: def __init__(self) -> None: self.parents: dict[object, object] = {} self.size: dict[object, int] = {} self.count: int = 0 def add(self, element: object) -> None: self.parents[element] = element self.size[element] = 1 ...
--- +++ @@ -1,8 +1,34 @@+""" +Union-Find (Disjoint Set) Data Structure + +A Union-Find data structure supporting add, find (root), and unite operations. +Uses union by size and path compression for near-constant amortized time. + +Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure + +Complexity: + ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/union_find.py
Annotate my code with docstrings
from __future__ import annotations def edit_distance(word_a: str, word_b: str) -> int: length_a, length_b = len(word_a) + 1, len(word_b) + 1 edit = [[0 for _ in range(length_b)] for _ in range(length_a)] for i in range(1, length_a): edit[i][0] = i for j in range(1, length_b): edit[...
--- +++ @@ -1,8 +1,35 @@+""" +Edit Distance (Levenshtein Distance) + +Find the minimum number of insertions, deletions, and substitutions +required to transform one word into another. + +Reference: https://en.wikipedia.org/wiki/Levenshtein_distance + +Complexity: + Time: O(m * n) where m, n are the lengths of the ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/edit_distance.py
Generate consistent docstrings
from __future__ import annotations def climb_stairs(steps: int) -> int: arr = [1, 1] for _ in range(1, steps): arr.append(arr[-1] + arr[-2]) return arr[-1] def climb_stairs_optimized(steps: int) -> int: a_steps = b_steps = 1 for _ in range(steps): a_steps, b_steps = b_steps, a_s...
--- +++ @@ -1,8 +1,38 @@+""" +Climbing Stairs + +Count the number of distinct ways to climb a staircase of n steps, +where each move is either 1 or 2 steps. + +Reference: https://leetcode.com/problems/climbing-stairs/ + +Complexity: + climb_stairs: + Time: O(n) + Space: O(n) + climb_stairs_optimize...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/climbing_stairs.py
Document this module using docstrings
from __future__ import annotations _INT_MAX = 32767 def egg_drop(n: int, k: int) -> int: egg_floor = [[0 for _ in range(k + 1)] for _ in range(n + 1)] for i in range(1, n + 1): egg_floor[i][1] = 1 egg_floor[i][0] = 0 for j in range(1, k + 1): egg_floor[1][j] = j for i in r...
--- +++ @@ -1,3 +1,15 @@+""" +Egg Drop Problem + +Given K eggs and a building with N floors, determine the minimum number +of moves needed to find the critical floor F in the worst case. + +Reference: https://en.wikipedia.org/wiki/Dynamic_programming#Egg_dropping_puzzle + +Complexity: + Time: O(n * k^2) + Space:...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/egg_drop.py
Write docstrings for algorithm functions
from __future__ import annotations def insert_one_bit(number: int, bit: int, position: int) -> int: upper = number >> position upper = (upper << 1) | bit upper = upper << position lower = ((1 << position) - 1) & number return lower | upper def insert_mult_bits(number: int, bits: int, length: in...
--- +++ @@ -1,8 +1,38 @@+""" +Insert Bit + +Insert one or more bits into an integer at a specific bit position. + +Reference: https://en.wikipedia.org/wiki/Bit_manipulation + +Complexity: + Time: O(1) + Space: O(1) +""" from __future__ import annotations def insert_one_bit(number: int, bit: int, position...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/insert_bit.py
Write docstrings for algorithm functions
from __future__ import annotations def gray_code(n: int) -> list[int]: return [i ^ (i >> 1) for i in range(1 << n)] def gray_to_binary(gray: int) -> int: mask = gray >> 1 while mask: gray ^= mask mask >>= 1 return gray
--- +++ @@ -1,14 +1,32 @@+"""Gray code — generate n-bit Gray code sequences. + +A Gray code is an ordering of binary numbers such that successive values +differ in exactly one bit. Used in error correction and rotary encoders. + +Inspired by PR #932 (Simranstha045). +""" from __future__ import annotations def g...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/gray_code.py
Document classes and their methods
from __future__ import annotations def house_robber(houses: list[int]) -> int: last, now = 0, 0 for house in houses: last, now = now, max(last + house, now) return now
--- +++ @@ -1,9 +1,33 @@+""" +House Robber + +Determine the maximum amount of money that can be robbed from a row of +houses without robbing two adjacent houses. + +Reference: https://leetcode.com/problems/house-robber/ + +Complexity: + Time: O(n) + Space: O(1) +""" from __future__ import annotations def...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/house_robber.py
Document functions with clear intent
from __future__ import annotations def hosoya(height: int, width: int) -> int: if (width == 0) and (height in (0, 1)): return 1 if (width == 1) and (height in (1, 2)): return 1 if height > width: return hosoya(height - 1, width) + hosoya(height - 2, width) if width == height: ...
--- +++ @@ -1,8 +1,33 @@+""" +Hosoya Triangle + +The Hosoya triangle (originally Fibonacci triangle) is a triangular arrangement +of numbers where each entry is the sum of two entries above it. + +Reference: https://en.wikipedia.org/wiki/Hosoya%27s_triangle + +Complexity: + Time: O(n^3) (naive recursive per entry)...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/hosoya_triangle.py
Create documentation strings for testing functions
from __future__ import annotations def has_alternative_bit(number: int) -> bool: first_bit = 0 second_bit = 0 while number: first_bit = number & 1 if number >> 1: second_bit = (number >> 1) & 1 if not first_bit ^ second_bit: return False els...
--- +++ @@ -1,8 +1,34 @@+""" +Has Alternating Bits + +Check whether a positive integer has alternating bits, meaning no two +adjacent bits share the same value. + +Reference: https://en.wikipedia.org/wiki/Bit_manipulation + +Complexity: + has_alternative_bit: O(number of bits) + has_alternative_bit_fast: O(1...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/has_alternative_bit.py
Write Python docstrings for this snippet
from __future__ import annotations def count(coins: list[int], value: int) -> int: dp_array = [1] + [0] * value for coin in coins: for i in range(coin, value + 1): dp_array[i] += dp_array[i - coin] return dp_array[value]
--- +++ @@ -1,12 +1,39 @@+""" +Coin Change (Number of Ways) + +Given a value and a set of coin denominations, count how many distinct +combinations of coins sum to the given value. + +Reference: https://leetcode.com/problems/coin-change-ii/ + +Complexity: + Time: O(n * m) where n is the value and m is the number o...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/coin_change.py
Add concise docstrings to each method
from __future__ import annotations def int_divide(decompose: int) -> int: arr = [[0 for i in range(decompose + 1)] for j in range(decompose + 1)] arr[1][1] = 1 for i in range(1, decompose + 1): for j in range(1, decompose + 1): if i < j: arr[i][j] = arr[i][i] ...
--- +++ @@ -1,8 +1,34 @@+""" +Integer Partition + +Count the number of ways a positive integer can be represented as a sum +of positive integers (order does not matter). + +Reference: https://en.wikipedia.org/wiki/Partition_(number_theory) + +Complexity: + Time: O(n^2) + Space: O(n^2) +""" from __future__ imp...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/int_divide.py
Write docstrings for algorithm functions
from __future__ import annotations class Job: def __init__(self, start: int, finish: int, profit: int) -> None: self.start = start self.finish = finish self.profit = profit def _binary_search(job: list[Job], start_index: int) -> int: left = 0 right = start_index - 1 while ...
--- +++ @@ -1,8 +1,21 @@+""" +Weighted Job Scheduling + +Given a set of jobs with start times, finish times, and profits, find +the maximum profit subset such that no two jobs overlap. + +Reference: https://en.wikipedia.org/wiki/Job-shop_scheduling + +Complexity: + Time: O(n^2) + Space: O(n) +""" from __futur...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/job_scheduling.py
Generate documentation strings for clarity
from __future__ import annotations class Item: def __init__(self, value: int, weight: int) -> None: self.value = value self.weight = weight def get_maximum_value(items: list[Item], capacity: int) -> int: dp = [0] * (capacity + 1) for item in items: for cur_weight in reversed(ra...
--- +++ @@ -1,8 +1,21 @@+""" +0/1 Knapsack Problem + +Given items with values and weights, and a knapsack capacity, find the +maximum total value that fits in the knapsack. + +Reference: https://en.wikipedia.org/wiki/Knapsack_problem + +Complexity: + Time: O(n * m) where n is the number of items and m is the capac...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/knapsack.py
Write Python docstrings for this snippet
from __future__ import annotations def num_decodings(enc_mes: str) -> int: if not enc_mes or enc_mes[0] == "0": return 0 last_char, last_two_chars = 1, 1 for i in range(1, len(enc_mes)): last = last_char if enc_mes[i] != "0" else 0 last_two = ( last_two_chars ...
--- +++ @@ -1,8 +1,34 @@+""" +Decode Ways + +Given an encoded message of digits, count the total number of ways to +decode it where 'A' = 1, 'B' = 2, ..., 'Z' = 26. + +Reference: https://leetcode.com/problems/decode-ways/ + +Complexity: + Time: O(n) + Space: O(1) for num_decodings, O(n) for num_decodings2 +""" ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/num_decodings.py
Add docstrings for production code
from __future__ import annotations def remove_bit(number: int, position: int) -> int: upper = number >> (position + 1) upper = upper << position lower = ((1 << position) - 1) & number return upper | lower
--- +++ @@ -1,9 +1,41 @@+""" +Remove Bit + +Remove a single bit at a specific position from an integer, shifting +higher bits down to fill the gap. + +Reference: https://en.wikipedia.org/wiki/Bit_manipulation + +Complexity: + Time: O(1) + Space: O(1) +""" from __future__ import annotations def remove_bit...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/remove_bit.py
Add clean documentation to messy code
from __future__ import annotations def longest_common_subsequence(s_1: str, s_2: str) -> int: m = len(s_1) n = len(s_2) mat = [[0] * (n + 1) for i in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: mat[i][j] = 0 elif s...
--- +++ @@ -1,8 +1,32 @@+""" +Longest Common Subsequence + +Find the length of the longest subsequence common to two strings. + +Reference: https://en.wikipedia.org/wiki/Longest_common_subsequence + +Complexity: + Time: O(m * n) + Space: O(m * n) +""" from __future__ import annotations def longest_common...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/longest_common_subsequence.py
Add docstrings to incomplete code
from __future__ import annotations def find_k_factor(length: int, k_factor: int) -> int: mat = [ [[0 for i in range(4)] for j in range((length - 1) // 3 + 2)] for k in range(length + 1) ] if 3 * k_factor + 1 > length: return 0 mat[1][0][0] = 1 mat[1][0][1] = 0 mat[1][...
--- +++ @@ -1,8 +1,36 @@+""" +K-Factor of a String + +The K factor of a string is the number of times 'abba' appears as a +substring. Given a length and a k_factor, count the number of strings of +that length whose K factor equals k_factor. + +Reference: https://en.wikipedia.org/wiki/Dynamic_programming + +Complexity: ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/k_factor.py
Insert docstrings into my code
from __future__ import annotations def single_number(nums: list[int]) -> int: result = 0 for number in nums: result ^= number return result
--- +++ @@ -1,9 +1,39 @@+""" +Single Number + +Given an array of integers where every element appears twice except for +one, find the unique element using XOR. + +Reference: https://en.wikipedia.org/wiki/Exclusive_or + +Complexity: + Time: O(n) + Space: O(1) +""" from __future__ import annotations def si...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/single_number.py
Generate docstrings with parameter types
from __future__ import annotations def longest_increasing_subsequence(sequence: list[int]) -> int: length = len(sequence) counts = [1 for _ in range(length)] for i in range(1, length): for j in range(0, i): if sequence[i] > sequence[j]: counts[i] = max(counts[i], count...
--- +++ @@ -1,8 +1,38 @@+""" +Longest Increasing Subsequence + +Find the length of the longest strictly increasing subsequence in an array. + +Reference: https://en.wikipedia.org/wiki/Longest_increasing_subsequence + +Complexity: + longest_increasing_subsequence: + Time: O(n^2) + Space: O(n) + long...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/longest_increasing.py
Auto-generate documentation strings for this file
from __future__ import annotations _INF = float("inf") def matrix_chain_order(array: list[int]) -> tuple[list[list[int]], list[list[int]]]: n = len(array) matrix = [[0 for x in range(n)] for x in range(n)] sol = [[0 for x in range(n)] for x in range(n)] for chain_length in range(2, n): for a...
--- +++ @@ -1,3 +1,15 @@+""" +Matrix Chain Multiplication + +Find the optimal parenthesization of a chain of matrices to minimize +the total number of scalar multiplications. + +Reference: https://en.wikipedia.org/wiki/Matrix_chain_multiplication + +Complexity: + Time: O(n^3) + Space: O(n^2) +""" from __futur...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/matrix_chain_order.py
Add docstrings with type hints explained
from __future__ import annotations from functools import reduce def max_product(nums: list[int]) -> int: lmin = lmax = gmax = nums[0] for num in nums[1:]: t_1 = num * lmax t_2 = num * lmin lmax = max(max(t_1, t_2), num) lmin = min(min(t_1, t_2), num) gmax = max(gmax, ...
--- +++ @@ -1,3 +1,18 @@+""" +Maximum Product Subarray + +Find the contiguous subarray within an array that has the largest product. + +Reference: https://leetcode.com/problems/maximum-product-subarray/ + +Complexity: + max_product: + Time: O(n) + Space: O(1) + subarray_with_max_product: + T...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/max_product_subarray.py
Add docstrings for internal functions
from __future__ import annotations def is_match(str_a: str, str_b: str) -> bool: len_a, len_b = len(str_a) + 1, len(str_b) + 1 matches = [[False] * len_b for _ in range(len_a)] matches[0][0] = True for i, element in enumerate(str_b[1:], 2): matches[0][i] = matches[0][i - 2] and element == "...
--- +++ @@ -1,8 +1,35 @@+""" +Regular Expression Matching + +Implement regular expression matching with support for '.' (matches any +single character) and '*' (matches zero or more of the preceding element). + +Reference: https://leetcode.com/problems/regular-expression-matching/ + +Complexity: + Time: O(m * n) + ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/regex_matching.py
Add docstrings to improve code quality
from __future__ import annotations def bellman_ford(graph: dict[str, dict[str, float]], source: str) -> bool: distance: dict[str, float] = {} predecessor: dict[str, str | None] = {} _initialize_single_source(graph, source, distance, predecessor) num_vertices = len(graph) for _ in range(1, num_v...
--- +++ @@ -1,8 +1,37 @@+""" +Bellman-Ford Algorithm for Single-Source Shortest Path + +Finds the shortest paths from a source vertex to all other vertices in a +weighted directed graph. Unlike Dijkstra's algorithm it can handle graphs +with negative edge weights. + +Reference: https://en.wikipedia.org/wiki/Bellman%E2...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/bellman_ford.py
Auto-generate documentation strings for this file
from __future__ import annotations def single_number2(nums: list[int]) -> int: ones, twos = 0, 0 for index in range(len(nums)): ones = (ones ^ nums[index]) & ~twos twos = (twos ^ nums[index]) & ~ones return ones
--- +++ @@ -1,10 +1,40 @@+""" +Single Number 2 + +Given an array of integers where every element appears three times except +for one (which appears exactly once), find that unique element using +constant space and linear time. + +Reference: https://en.wikipedia.org/wiki/Exclusive_or + +Complexity: + Time: O(n) + ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/single_number2.py
Add documentation for all methods
from __future__ import annotations def get_factors(n: int) -> list[list[int]]: def _factor( n: int, i: int, combi: list[int], res: list[list[int]], ) -> list[list[int]]: while i * i <= n: if n % i == 0: res += (combi + [i, int(n / i)],) ...
--- +++ @@ -1,8 +1,32 @@+""" +Factor Combinations + +Given an integer n, return all possible combinations of its factors +(excluding 1 and n itself in the factorisation). + +Reference: https://leetcode.com/problems/factor-combinations/ + +Complexity: + Time: O(n^(1/2) * log n) (approximate, depends on factor densi...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/all_factors.py
Add missing documentation to my Python functions
from __future__ import annotations _INT_MIN = -32767 def cut_rod(price: list[int]) -> int: n = len(price) val = [0] * (n + 1) for i in range(1, n + 1): max_val = _INT_MIN for j in range(i): max_val = max(max_val, price[j] + val[i - j - 1]) val[i] = max_val retur...
--- +++ @@ -1,3 +1,15 @@+""" +Rod Cutting Problem + +Given a rod of length n and a list of prices for each piece length, +determine the maximum revenue obtainable by cutting and selling the pieces. + +Reference: https://en.wikipedia.org/wiki/Cutting_stock_problem + +Complexity: + Time: O(n^2) + Space: O(n) +""" ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/rod_cut.py
Add documentation for all methods
from __future__ import annotations from collections import deque def check_bipartite(adj_list: list[list[int]]) -> bool: vertices = len(adj_list) set_type = [-1 for _ in range(vertices)] set_type[0] = 0 queue = deque([0]) while queue: current = queue.popleft() if adj_list[cur...
--- +++ @@ -1,3 +1,14 @@+""" +Check Bipartite Graph + +Determine whether an undirected graph is bipartite using BFS colouring. + +Reference: https://en.wikipedia.org/wiki/Bipartite_graph + +Complexity: + Time: O(V^2) (adjacency-matrix representation) + Space: O(V) +""" from __future__ import annotations @@...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/check_bipartite.py
Add verbose docstrings with examples
from __future__ import annotations def is_power_of_two(number: int) -> bool: return number > 0 and not number & (number - 1)
--- +++ @@ -1,6 +1,35 @@+""" +Power of Two + +Determine whether a given integer is a power of two using bit manipulation. +A power of two has exactly one set bit, so ``n & (n - 1)`` clears that bit +and yields zero. + +Reference: https://en.wikipedia.org/wiki/Power_of_two + +Complexity: + Time: O(1) + Space: O(1...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/power_of_two.py
Generate consistent documentation across files
from __future__ import annotations from collections import defaultdict class Graph: def __init__(self, vertex_count: int) -> None: self.vertex_count = vertex_count self.graph: dict[int, list[int]] = defaultdict(list) def add_edge(self, source: int, target: int) -> None: self.graph[...
--- +++ @@ -1,3 +1,16 @@+""" +Check if a Directed Graph is Strongly Connected + +A directed graph is strongly connected if every vertex is reachable from +every other vertex. This implementation uses two DFS passes (one on the +original graph and one on the reversed graph). + +Reference: https://en.wikipedia.org/wiki/...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/check_digraph_strongly_connected.py
Write clean docstrings for readability
from __future__ import annotations from math import sqrt def planting_trees(trees: list[int], length: int, width: int) -> float: trees = [0] + trees n_pairs = int(len(trees) / 2) space_between_pairs = length / (n_pairs - 1) target_locations = [location * space_between_pairs for location in range(...
--- +++ @@ -1,3 +1,16 @@+""" +Planting Trees + +Given an even number of trees along one side of a road, calculate the +minimum total distance to move them into valid positions on both sides +at even intervals. + +Reference: https://en.wikipedia.org/wiki/Dynamic_programming + +Complexity: + Time: O(n^2) + Space: ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/planting_trees.py
Write docstrings that follow conventions
from __future__ import annotations def reverse_bits(number: int) -> int: result = 0 for _ in range(32): result = (result << 1) + (number & 1) number >>= 1 return result
--- +++ @@ -1,10 +1,35 @@+""" +Reverse Bits + +Reverse the bits of a 32-bit unsigned integer. + +Reference: https://en.wikipedia.org/wiki/Bit_reversal + +Complexity: + Time: O(1) -- always iterates exactly 32 times + Space: O(1) +""" from __future__ import annotations def reverse_bits(number: int) -> int...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/reverse_bits.py
Add docstrings to my Python code
from __future__ import annotations from dataclasses import dataclass @dataclass class ListNode: val: int = 0 next: ListNode | None = None
--- +++ @@ -1,3 +1,10 @@+"""Singly linked list node shared across all linked list algorithms. + +This module provides the universal ListNode used by every linked list +algorithm in this library. Using a single shared type means you can +compose algorithms: merge two lists, reverse the result, check if +it's a palindrom...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/common/list_node.py
Add verbose docstrings with examples
from __future__ import annotations def subsets(nums: list[int]) -> set[tuple[int, ...]]: length = len(nums) total = 1 << length result: set[tuple[int, ...]] = set() for mask in range(total): subset = tuple( number for bit_index, number in enumerate(nums) if mask & 1 << bit_index ...
--- +++ @@ -1,8 +1,35 @@+""" +Subsets via Bit Manipulation + +Generate all possible subsets of a set of distinct integers using bitmask +enumeration. Each integer from 0 to 2^n - 1 represents a unique subset. + +Reference: https://en.wikipedia.org/wiki/Power_set + +Complexity: + Time: O(n * 2^n) + Space: O(n * 2...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/subsets.py
Document this script properly
from __future__ import annotations import heapq from collections.abc import Callable from typing import Any def a_star( graph: dict[Any, list[tuple[Any, float]]], start: Any, goal: Any, h: Callable[[Any], float], ) -> tuple[list[Any] | None, float]: open_set: list[tuple[float, float, Any, list[A...
--- +++ @@ -1,3 +1,14 @@+""" +A* (A-star) Search Algorithm + +Finds the shortest path in a weighted graph using a heuristic function. + +Reference: https://en.wikipedia.org/wiki/A*_search_algorithm + +Complexity: + Time: O(E log V) with a binary heap + Space: O(V) +""" from __future__ import annotations @@ ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/a_star.py
Add docstrings that explain purpose and usage
from __future__ import annotations from algorithms.data_structures.union_find import Union def num_islands(positions: list[list[int]]) -> list[int]: result: list[int] = [] islands = Union() for position in map(tuple, positions): islands.add(position) for delta in (0, 1), (0, -1), (1, 0),...
--- +++ @@ -1,3 +1,16 @@+""" +Count Islands via Union-Find + +Uses the Union-Find (Disjoint Set) data structure to solve the "Number of +Islands" problem. After each addLand operation, counts distinct connected +components of land cells. + +Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure + +Complex...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/count_islands_unionfind.py
Write docstrings describing each step
from __future__ import annotations def swap_pair(number: int) -> int: odd_bits = (number & int("AAAAAAAA", 16)) >> 1 even_bits = (number & int("55555555", 16)) << 1 return odd_bits | even_bits
--- +++ @@ -1,8 +1,38 @@+""" +Swap Pair + +Swap odd and even bits of an integer using bitmask operations. Bit 0 is +swapped with bit 1, bit 2 with bit 3, and so on. + +Reference: https://en.wikipedia.org/wiki/Bit_manipulation + +Complexity: + Time: O(1) + Space: O(1) +""" from __future__ import annotations ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/swap_pair.py
Add well-formatted docstrings
from __future__ import annotations def num_islands(grid: list[list[int]]) -> int: count = 0 for i in range(len(grid)): for j, col in enumerate(grid[i]): if col == 1: _dfs(grid, i, j) count += 1 return count def _dfs(grid: list[list[int]], i: int, j: i...
--- +++ @@ -1,8 +1,32 @@+""" +Count Islands (DFS) + +Given a 2D grid of 1s (land) and 0s (water), count the number of islands +using depth-first search. + +Reference: https://leetcode.com/problems/number-of-islands/ + +Complexity: + Time: O(M * N) + Space: O(M * N) recursion stack in worst case +""" from __fu...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/count_islands_dfs.py
Write docstrings including parameters and return values
from __future__ import annotations from collections import deque def count_islands(grid: list[list[int]]) -> int: row = len(grid) col = len(grid[0]) num_islands = 0 visited = [[0] * col for _ in range(row)] directions = [[-1, 0], [1, 0], [0, -1], [0, 1]] queue: deque[tuple[int, int]] = dequ...
--- +++ @@ -1,3 +1,16 @@+""" +Count Islands (BFS) + +Given a 2D grid of 1s (land) and 0s (water), count the number of islands +using breadth-first search. An island is a group of adjacent lands +connected horizontally or vertically. + +Reference: https://leetcode.com/problems/number-of-islands/ + +Complexity: + Tim...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/count_islands_bfs.py
Provide clean and structured docstrings
from __future__ import annotations def count_components(adjacency_list: list[list[int]], size: int) -> int: count = 0 visited = [False] * (size + 1) for i in range(1, size + 1): if not visited[i]: _dfs(i, visited, adjacency_list) count += 1 return count def _dfs( ...
--- +++ @@ -1,8 +1,33 @@+""" +Count Connected Components in an Undirected Graph + +Uses DFS to count the number of connected components. + +Reference: https://en.wikipedia.org/wiki/Component_(graph_theory) + +Complexity: + Time: O(V + E) + Space: O(V) +""" from __future__ import annotations def count_com...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/count_connected_number_of_component.py
Generate consistent docstrings
from __future__ import annotations from typing import Any def find_path( graph: dict[Any, list[Any]], start: Any, end: Any, path: list[Any] | None = None, ) -> list[Any] | None: if path is None: path = [] path = path + [start] if start == end: return path if start not...
--- +++ @@ -1,3 +1,13 @@+""" +Find Paths in a Graph + +Provides functions to find a single path, all paths, or the shortest path +between two nodes using recursion and backtracking. + +Complexity: + Time: O(V!) worst case (exponential backtracking) + Space: O(V) per recursion stack +""" from __future__ import...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/find_path.py
Insert docstrings into my code
from __future__ import annotations def find_all_cliques(edges: dict[str, set[str]]) -> list[list[str]]: compsub: list[str] = [] solutions: list[list[str]] = [] def _expand_clique(candidates: set[str], nays: set[str]) -> None: if not candidates and not nays: solutions.append(compsub.c...
--- +++ @@ -1,8 +1,32 @@+""" +Find All Cliques (Bron-Kerbosch) + +Finds every maximal clique in an undirected graph. + +Reference: Bron, Coen; Kerbosch, Joep (1973), "Algorithm 457: finding all + cliques of an undirected graph", Communications of the ACM. + +Complexity: + Time: O(3^(V/3)) worst case + Space: ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/find_all_cliques.py
Write Python docstrings for this snippet
from __future__ import annotations import heapq from collections import defaultdict, deque class Node: def __init__( self, frequency: int = 0, sign: int | None = None, left: Node | None = None, right: Node | None = None, ) -> None: self.frequency = frequency ...
--- +++ @@ -1,3 +1,16 @@+""" +Huffman Coding + +An efficient method of lossless data compression. Symbols appearing more +frequently are encoded with shorter bit strings while less frequent symbols +receive longer codes. + +Reference: https://en.wikipedia.org/wiki/Huffman_coding + +Complexity: + Time: O(n log n) fo...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/compression/huffman_coding.py
Can you add docstrings to this Python file?
from __future__ import annotations def single_number3(nums: list[int]) -> list[int]: xor_both = 0 for number in nums: xor_both ^= number rightmost_set_bit = xor_both & (-xor_both) first, second = 0, 0 for number in nums: if number & rightmost_set_bit: first ^= number...
--- +++ @@ -1,8 +1,37 @@+""" +Single Number 3 + +Given an array where exactly two elements appear once and all others +appear exactly twice, find those two unique elements in O(n) time and +O(1) space. + +Reference: https://en.wikipedia.org/wiki/Exclusive_or + +Complexity: + Time: O(n) + Space: O(1) +""" from...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/bit_manipulation/single_number3.py
Add docstrings with type hints explained
from __future__ import annotations def pacific_atlantic(matrix: list[list[int]]) -> list[list[int]]: n = len(matrix) if not n: return [] m = len(matrix[0]) if not m: return [] res: list[list[int]] = [] atlantic = [[False for _ in range(n)] for _ in range(m)] pacific = [[Fa...
--- +++ @@ -1,8 +1,33 @@+""" +Pacific Atlantic Water Flow + +Given an m*n matrix of heights, find all cells from which water can flow +to both the Pacific (top / left edges) and Atlantic (bottom / right edges) +oceans. + +Reference: https://leetcode.com/problems/pacific-atlantic-water-flow/ + +Complexity: + Time: O...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/pacific_atlantic.py
Add docstrings to improve collaboration
from __future__ import annotations from collections import deque class Solution: def topological_sort( self, vertices: int, adj: list[list[int]] ) -> list[int]: in_degree = [0] * vertices for i in range(vertices): for neighbor in adj[i]: in_degree[neighbo...
--- +++ @@ -1,3 +1,15 @@+""" +Kahn's Algorithm (Topological Sort via BFS) + +Computes a topological ordering of a directed acyclic graph using an +in-degree based BFS approach. + +Reference: https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm + +Complexity: + Time: O(V + E) + Space: O(V) +""" f...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/kahns_algorithm.py
Write docstrings describing each step
from __future__ import annotations from dataclasses import dataclass, field @dataclass class Graph: adj: dict[str, dict[str, float]] = field(default_factory=dict) directed: bool = True @classmethod def unweighted(cls, adj: dict[str, list[str]], directed: bool = True) -> Graph: weighted = {...
--- +++ @@ -1,3 +1,10 @@+"""Graph type shared across all graph algorithms. + +This module provides the universal Graph used by every graph algorithm +in this library. Using a single shared type means you can compose +algorithms: build a graph, run BFS to check connectivity, then run +Dijkstra for shortest paths — all o...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/common/graph.py
Please document this code using docstrings
from __future__ import annotations from collections import defaultdict class Graph: def __init__(self, vertex_count: int) -> None: self.vertex_count = vertex_count self.graph: dict[int, list[int]] = defaultdict(list) self.has_path = False def add_edge(self, source: int, target: int...
--- +++ @@ -1,3 +1,13 @@+""" +Path Between Two Vertices in a Directed Graph + +Determines whether there is a directed path from a source vertex to a +target vertex using DFS. + +Complexity: + Time: O(V + E) + Space: O(V) +""" from __future__ import annotations @@ -5,20 +15,45 @@ class Graph: + """A d...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/path_between_two_vertices_in_digraph.py
Insert docstrings into my code
from __future__ import annotations def fib_recursive(n: int) -> int: assert n >= 0, "n must be a positive integer" if n <= 1: return n return fib_recursive(n - 1) + fib_recursive(n - 2) def fib_list(n: int) -> int: assert n >= 0, "n must be a positive integer" list_results = [0, 1] ...
--- +++ @@ -1,8 +1,39 @@+""" +Fibonacci Number + +Compute the n-th Fibonacci number using three different approaches: +recursive, list-based DP, and iterative. + +Reference: https://en.wikipedia.org/wiki/Fibonacci_number + +Complexity: + fib_recursive: + Time: O(2^n) + Space: O(n) (call stack) + f...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/fib.py
Generate descriptive docstrings automatically
from __future__ import annotations def gale_shapley( men: dict[str, list[str]], women: dict[str, list[str]], ) -> dict[str, str]: men_available: list[str] = list(men.keys()) married: dict[str, str] = {} proposal_counts: dict[str, int] = {man: 0 for man in men} while men_available: ma...
--- +++ @@ -1,3 +1,16 @@+""" +Gale-Shapley Stable Matching + +Solves the stable matching (stable marriage) problem. Given N men and N women +with ranked preferences, produces a stable matching where no pair would prefer +each other over their current partners. + +Reference: https://en.wikipedia.org/wiki/Gale%E2%80%93Sh...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/greedy/gale_shapley.py
Write docstrings for backend logic
from __future__ import annotations def word_break(word: str, word_dict: set[str]) -> bool: dp_array = [False] * (len(word) + 1) dp_array[0] = True for i in range(1, len(word) + 1): for j in range(0, i): if dp_array[j] and word[j:i] in word_dict: dp_array[i] = True ...
--- +++ @@ -1,8 +1,35 @@+""" +Word Break + +Given a string and a dictionary of words, determine whether the string +can be segmented into a sequence of dictionary words. + +Reference: https://leetcode.com/problems/word-break/ + +Complexity: + Time: O(n^2) + Space: O(n) +""" from __future__ import annotations ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/word_break.py
Annotate my code with docstrings
from __future__ import annotations from heapq import heapify, heappop, heapreplace class ListNode: def __init__(self, val: int) -> None: self.val = val self.next: ListNode | None = None def merge_k_lists(lists: list[ListNode | None]) -> ListNode | None: dummy = node = ListNode(0) heap...
--- +++ @@ -1,3 +1,15 @@+""" +Merge K Sorted Linked Lists + +Merge k sorted linked lists into one sorted linked list using a heap +for efficient minimum extraction. + +Reference: https://leetcode.com/problems/merge-k-sorted-lists/ + +Complexity: + Time: O(n log k) where n is total elements and k is number of lists ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/heap/merge_sorted_k_lists.py
Generate docstrings for exported functions
from __future__ import annotations def _helper_topdown(nums: list[int], target: int, dp: list[int]) -> int: if dp[target] != -1: return dp[target] result = 0 for num in nums: if target >= num: result += _helper_topdown(nums, target - num, dp) dp[target] = result return...
--- +++ @@ -1,8 +1,34 @@+""" +Combination Sum IV + +Given an array of distinct positive integers and a target, find the number +of possible combinations (order matters) that add up to the target. + +Reference: https://leetcode.com/problems/combination-sum-iv/ + +Complexity: + combination_sum_topdown: + Time: ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/combination_sum.py
Generate NumPy-style docstrings
from __future__ import annotations class Kosaraju: def dfs( self, i: int, vertices: int, adj: list[list[int]], visited: list[int], stk: list[int], ) -> None: visited[i] = 1 for x in adj[i]: if visited[x] == -1: self...
--- +++ @@ -1,8 +1,21 @@+""" +Strongly Connected Components (Kosaraju's Algorithm) + +Counts the number of strongly connected components in a directed graph +using two DFS passes. + +Reference: https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm + +Complexity: + Time: O(V + E) + Space: O(V + E) +""" from __f...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/strongly_connected_components_kosaraju.py
Add professional docstrings to my codebase
from __future__ import annotations from enum import Enum class TraversalState(Enum): WHITE = 0 GRAY = 1 BLACK = 2 def is_in_cycle( graph: dict[str, list[str]], traversal_states: dict[str, TraversalState], vertex: str, ) -> bool: if traversal_states[vertex] == TraversalState.GRAY: ...
--- +++ @@ -1,3 +1,15 @@+""" +Cycle Detection in a Directed Graph + +Uses DFS with three-colour marking to determine whether a directed graph +contains a cycle. + +Reference: https://en.wikipedia.org/wiki/Cycle_(graph_theory) + +Complexity: + Time: O(V + E) + Space: O(V) +""" from __future__ import annotation...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/cycle_detection.py
Improve documentation using docstrings
from __future__ import annotations from heapq import heapify, heappushpop def k_closest( points: list[tuple[int, int]], k: int, origin: tuple[int, int] = (0, 0), ) -> list[tuple[int, int]]: heap = [(-_distance(p, origin), p) for p in points[:k]] heapify(heap) for point in points[k:]: ...
--- +++ @@ -1,3 +1,16 @@+""" +K Closest Points to Origin + +Given a list of points, find the k closest to the origin using a max +heap of size k. For each subsequent point, replace the heap root if +the new point is closer. + +Reference: https://leetcode.com/problems/k-closest-points-to-origin/ + +Complexity: + Time...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/heap/k_closest_points.py
Add docstrings to improve code quality
class Fenwick_Tree: # noqa: N801 def __init__(self, freq): self.arr = freq self.n = len(freq) def get_sum(self, bit_tree, i): s = 0 # index in bit_tree[] is 1 more than the index in arr[] i = i + 1 # Traverse ancestors of bit_tree[index] while i > 0...
--- +++ @@ -1,3 +1,30 @@+""" +Fenwick Tree / Binary Indexed Tree + +Consider we have an array arr[0 . . . n-1]. We would like to +1. Compute the sum of the first i elements. +2. Modify the value of a specified element of the array + arr[i] = x where 0 <= i <= n-1. + +A simple solution is to run a loop from 0 to i-1 a...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/fenwick_tree.py
Write documentation strings for class attributes
from __future__ import annotations import heapq from typing import Any def prims_minimum_spanning( graph_used: dict[Any, list[list[int | Any]]], ) -> int: vis: list[Any] = [] heap: list[list[int | Any]] = [[0, 1]] prim: set[Any] = set() mincost = 0 while len(heap) > 0: cost, node = ...
--- +++ @@ -1,3 +1,15 @@+""" +Prim's Minimum Spanning Tree + +Computes the weight of a minimum spanning tree for a connected weighted +undirected graph using a priority queue. + +Reference: https://en.wikipedia.org/wiki/Prim%27s_algorithm + +Complexity: + Time: O(E log V) + Space: O(V + E) +""" from __future_...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/prims_minimum_spanning.py
Include argument descriptions in docstrings
from __future__ import annotations import collections class UndirectedGraphNode: def __init__(self, label: int) -> None: self.label = label self.neighbors: list[UndirectedGraphNode] = [] def shallow_copy(self) -> UndirectedGraphNode: return UndirectedGraphNode(self.label) def ...
--- +++ @@ -1,3 +1,15 @@+""" +Clone an Undirected Graph + +Each node contains a label and a list of its neighbours. Three strategies +are provided: BFS-based, iterative DFS, and recursive DFS. + +Reference: https://leetcode.com/problems/clone-graph/ + +Complexity: + Time: O(V + E) + Space: O(V) +""" from __f...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/clone_graph.py
Add verbose docstrings with examples
from __future__ import annotations def max_contiguous_subsequence_sum(arr: list[int]) -> int: if not arr: return 0 max_sum = arr[0] current_sum = 0 for value in arr: if current_sum + value < value: current_sum = value else: current_sum += value ...
--- +++ @@ -1,8 +1,39 @@+""" +Maximum Contiguous Subsequence Sum (Kadane's Algorithm) + +Finds the maximum sum of a contiguous sub-array within a one-dimensional +array of numbers. The algorithm is greedy / dynamic-programming hybrid. + +Reference: https://en.wikipedia.org/wiki/Maximum_subarray_problem + +Complexity: ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/greedy/max_contiguous_subsequence_sum.py
Generate missing documentation strings
from __future__ import annotations from algorithms.graph.graph import DirectedGraph class Tarjan: def __init__(self, dict_graph: dict[str, list[str]]) -> None: self.graph = DirectedGraph(dict_graph) self.index = 0 self.stack: list = [] for vertex in self.graph.nodes: ...
--- +++ @@ -1,3 +1,14 @@+""" +Tarjan's Strongly Connected Components Algorithm + +Finds all strongly connected components in a directed graph. + +Reference: https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm + +Complexity: + Time: O(V + E) + Space: O(V) +""" from __future__ impor...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/tarjan.py
Write clean docstrings for readability
class RBNode: def __init__(self, val, is_red, parent=None, left=None, right=None): self.val = val self.parent = parent self.left = left self.right = right self.color = is_red class RBTree: def __init__(self): self.root = None def left_rotate(self, node): ...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation of Red-Black tree. +""" class RBNode: @@ -137,6 +140,12 @@ self.root.color = 0 def transplant(self, node_u, node_v): + """ + replace u with v + :param node_u: replaced node + :param node_v: + :return: None + """ ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/red_black_tree.py
Add standardized docstrings across the file
from __future__ import annotations class Node: def __init__(self, name: str) -> None: self.name = name @staticmethod def get_name(obj: object) -> str: if isinstance(obj, Node): return obj.name if isinstance(obj, str): return obj return "" def...
--- +++ @@ -1,14 +1,29 @@+""" +Graph Data Structures + +Reusable classes for representing nodes, directed edges and directed graphs. +These can be shared across graph algorithms. +""" from __future__ import annotations class Node: + """A node (vertex) in a graph.""" def __init__(self, name: str) -> No...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/graph.py
Help me add docstrings to my project
from __future__ import annotations import collections def max_sliding_window(nums: list[int], k: int) -> list[int]: if not nums: return nums queue: collections.deque[int] = collections.deque() result: list[int] = [] for num in nums: if len(queue) < k: queue.append(num) ...
--- +++ @@ -1,3 +1,15 @@+""" +Sliding Window Maximum (Heap-based) + +Given an array and a window size k, find the maximum element in each +sliding window using a deque that maintains decreasing order of values. + +Reference: https://leetcode.com/problems/sliding-window-maximum/ + +Complexity: + Time: O(n) + Spac...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/heap/sliding_window_max.py
Write clean docstrings for readability
from __future__ import annotations class Node: def __init__(self, x: object) -> None: self.val = x self.next: Node | None = None def is_cyclic(head: Node | None) -> bool: if not head: return False runner = head walker = head while runner.next and runner.next.next: ...
--- +++ @@ -1,3 +1,15 @@+""" +Linked List Cycle Detection + +Given a linked list, determine if it has a cycle using Floyd's Tortoise and +Hare algorithm without extra space. + +Reference: https://leetcode.com/problems/linked-list-cycle/ + +Complexity: + Time: O(n) + Space: O(1) +""" from __future__ import ann...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/is_cyclic.py
Turn comments into proper docstrings
from __future__ import annotations from collections import deque def max_matching(n: int, edges: list[tuple[int, int]]) -> list[tuple[int, int]]: adj: list[list[int]] = [[] for _ in range(n)] for u, v in edges: adj[u].append(v) adj[v].append(u) match = [-1] * n def find_augmenting_...
--- +++ @@ -1,3 +1,13 @@+"""Edmonds' blossom algorithm — maximum cardinality matching. + +Finds a maximum matching in a general (non-bipartite) undirected graph. +The algorithm handles odd-length cycles ("blossoms") by contracting them +and recursing. + +Time: O(V^2 * E). + +Inspired by PR #826 (abhishekiitm). +""" ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/blossom.py
Generate helpful docstrings for debugging
from __future__ import annotations from typing import Any def _dfs_transposed( vertex: Any, graph: dict[Any, list[Any]], order: list[Any], visited: dict[Any, bool], ) -> None: visited[vertex] = True for adjacent in graph[vertex]: if not visited[adjacent]: _dfs_transposed(...
--- +++ @@ -1,3 +1,16 @@+""" +2-SAT Satisfiability + +Given a formula in conjunctive normal form (2-CNF), finds an assignment of +True/False values that satisfies all clauses, or reports that no solution +exists. + +Reference: https://en.wikipedia.org/wiki/2-satisfiability + +Complexity: + Time: O(V + E) + Space...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/satisfiability.py
Generate missing documentation strings
from __future__ import annotations import math def tsp(dist: list[list[float]]) -> float: n = len(dist) full_mask = (1 << n) - 1 dp: dict[tuple[int, int], float] = {} def solve(mask: int, pos: int) -> float: if mask == full_mask: return dist[pos][0] key = (mask, pos) ...
--- +++ @@ -1,3 +1,13 @@+"""Bitmask dynamic programming — Travelling Salesman Problem (TSP). + +Uses DP with bitmask to find the minimum-cost Hamiltonian cycle in a +weighted graph. The state (visited_mask, current_city) encodes which +cities have been visited and where we are now. + +Time: O(2^n * n^2). Space: O(2^n ...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/bitmask.py
Provide clean and structured docstrings
from __future__ import annotations class Sudoku: def __init__( self, board: list[list[str]], row: int, col: int, ) -> None: self.board = board self.row = row self.col = col self.val = self._possible_values() def _possible_values(self) -> d...
--- +++ @@ -1,8 +1,21 @@+""" +Sudoku Solver (DFS / Backtracking) + +Solves a Sudoku puzzle using constraint propagation and depth-first search +with backtracking, starting from the cell with the fewest possible values. + +Reference: https://leetcode.com/problems/sudoku-solver/ + +Complexity: + Time: O(9^(empty cell...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/sudoku_solver.py
Create docstrings for API functions
from __future__ import annotations from abc import ABCMeta, abstractmethod from collections.abc import Iterator class AbstractQueue(metaclass=ABCMeta): def __init__(self) -> None: self._size = 0 def __len__(self) -> int: return self._size def is_empty(self) -> bool: return sel...
--- +++ @@ -1,3 +1,15 @@+""" +Queue Abstract Data Type + +Implementations of the queue ADT using both a fixed-size array and a +linked list. Both support enqueue, dequeue, peek, is_empty, len, and iter. + +Reference: https://en.wikipedia.org/wiki/Queue_(abstract_data_type) + +Complexity: + Time: O(1) for enqueue/de...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/data_structures/queue.py
Add docstrings explaining edge cases
from __future__ import annotations from queue import Queue def _dfs( capacity: list[list[int]], flow: list[list[int]], visit: list[bool], vertices: int, idx: int, sink: int, current_flow: int = 1 << 63, ) -> int: if idx == sink: return current_flow visit[idx] = True f...
--- +++ @@ -1,3 +1,16 @@+""" +Maximum Flow Algorithms + +Implements Ford-Fulkerson (DFS), Edmonds-Karp (BFS) and Dinic's algorithm +for computing maximum flow in a flow network. + +Reference: https://en.wikipedia.org/wiki/Maximum_flow_problem + +Complexity: + Ford-Fulkerson: O(E * f) where f is the max flow value +...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/maximum_flow.py
Generate NumPy-style docstrings
from __future__ import annotations class Node: def __init__(self, x: int) -> None: self.val = x self.next: Node | None = None def swap_pairs(head: Node | None) -> Node | None: if not head: return head sentinel = Node(0) sentinel.next = head current = sentinel while c...
--- +++ @@ -1,3 +1,15 @@+""" +Swap Nodes in Pairs + +Given a linked list, swap every two adjacent nodes and return the new head. +Only node links are changed, not node values. + +Reference: https://leetcode.com/problems/swap-nodes-in-pairs/ + +Complexity: + Time: O(n) + Space: O(1) +""" from __future__ import...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/swap_in_pairs.py
Document helper functions with docstrings
from __future__ import annotations import heapq def get_skyline(lrh: list[list[int]]) -> list[list[int]]: skyline: list[list[int]] = [] live: list[list[int]] = [] i, n = 0, len(lrh) while i < n or live: if not live or i < n and lrh[i][0] <= -live[0][1]: x = lrh[i][0] ...
--- +++ @@ -1,3 +1,15 @@+""" +Skyline Problem + +Given building triplets [left, right, height], compute the skyline +contour as a list of key points using a heap-based sweep line approach. + +Reference: https://leetcode.com/problems/the-skyline-problem/ + +Complexity: + Time: O(n log n) + Space: O(n) +""" fro...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/heap/skyline.py
Document functions with detailed explanations
from __future__ import annotations class Node: def __init__(self, val: object = None) -> None: self.val = int(val) self.next: Node | None = None def partition(head: Node | None, x: int) -> None: left = None right = None prev = None current = head while current: if in...
--- +++ @@ -1,3 +1,15 @@+""" +Partition Linked List + +Partition a linked list around a value x so that all nodes with values less +than x come before nodes with values greater than or equal to x. + +Reference: https://leetcode.com/problems/partition-list/ + +Complexity: + Time: O(n) + Space: O(1) +""" from _...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/partition.py
Write documentation strings for class attributes
from __future__ import annotations class Node: def __init__(self, val: object = None) -> None: self.val = val self.next: Node | None = None def intersection(h1: Node, h2: Node) -> Node | None: count = 0 flag = None h1_orig = h1 h2_orig = h2 while h1 or h2: count += ...
--- +++ @@ -1,3 +1,15 @@+""" +Intersection of Two Linked Lists + +Given two singly linked lists that converge at some node, find and return the +intersecting node. The node identity (not value) is the unique identifier. + +Reference: https://leetcode.com/problems/intersection-of-two-linked-lists/ + +Complexity: + Ti...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/intersection.py
Fill in missing docstrings in my code
from __future__ import annotations def remove_range(head: object | None, start: int, end: int) -> object | None: assert start <= end if start == 0: for _ in range(end + 1): if head is not None: head = head.next else: current = head for _ in range(start ...
--- +++ @@ -1,8 +1,34 @@+""" +Remove Range from Linked List + +Given a linked list and a start and end index, remove the elements at those +indexes (inclusive) from the list. + +Reference: https://en.wikipedia.org/wiki/Linked_list + +Complexity: + Time: O(n) + Space: O(1) +""" from __future__ import annotatio...
https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/remove_range.py