instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Write documentation strings for class attributes |
from __future__ import annotations
def is_sorted(head: object | None) -> bool:
if not head:
return True
current = head
while current.next:
if current.val > current.next.val:
return False
current = current.next
return True | --- +++ @@ -1,8 +1,32 @@+"""
+Is Sorted Linked List
+
+Given a linked list, determine whether the list is sorted in non-decreasing
+order. An empty list is considered sorted.
+
+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/is_sorted.py |
Help me document legacy Python code |
from __future__ import annotations
class Dijkstra:
def __init__(self, vertex_count: int) -> None:
self.vertex_count = vertex_count
self.graph: list[list[int]] = [
[0 for _ in range(vertex_count)] for _ in range(vertex_count)
]
def min_distance(self, dist: list[float], mi... | --- +++ @@ -1,16 +1,43 @@+"""
+Dijkstra's Single-Source Shortest-Path Algorithm
+
+Finds shortest distances from a source vertex to every other vertex in a
+graph with non-negative edge weights.
+
+Reference: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
+
+Complexity:
+ Time: O(V^2) (adjacency-matrix repre... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/dijkstra.py |
Provide clean and structured docstrings |
from __future__ import annotations
import random
from collections.abc import Iterator
from typing import Any
def _choose_state(state_map: dict[Any, float]) -> Any | None:
choice = random.random()
probability_reached = 0.0
for state, probability in state_map.items():
probability_reached += probab... | --- +++ @@ -1,3 +1,15 @@+"""
+Markov Chain
+
+Provides utilities for stepping through and iterating a discrete Markov chain
+described as a dictionary of transition probabilities.
+
+Reference: https://en.wikipedia.org/wiki/Markov_chain
+
+Complexity:
+ Time: O(S) per step, where S is the number of states
+ Spac... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/markov_chain.py |
Document this script properly |
from __future__ import annotations
import heapq
def dijkstra(
graph: dict[str, dict[str, int | float]],
source: str,
target: str = "",
) -> tuple[int | float, list[str]]:
dist: dict[str, int | float] = {v: float("inf") for v in graph}
dist[source] = 0
prev: dict[str, str | None] = {v: None f... | --- +++ @@ -1,3 +1,18 @@+"""
+Dijkstra's Shortest-Path Algorithm (Heap-Optimised)
+
+Computes single-source shortest paths in a graph with non-negative edge
+weights using a min-heap (priority queue) for efficient vertex selection.
+
+This adjacency-list implementation is faster than the O(V²) matrix version
+for spars... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/dijkstra_heapq.py |
Add inline docstrings for readability |
from __future__ import annotations
def rotate_right(head: object | None, k: int) -> object | None:
if not head or not head.next:
return head
current = head
length = 1
while current.next:
current = current.next
length += 1
current.next = head
k = k % length
for _ in... | --- +++ @@ -1,8 +1,33 @@+"""
+Rotate List
+
+Given a linked list, rotate the list to the right by k places, where k is
+non-negative.
+
+Reference: https://leetcode.com/problems/rotate-list/
+
+Complexity:
+ Time: O(n)
+ Space: O(1)
+"""
from __future__ import annotations
def rotate_right(head: object | ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/rotate_list.py |
Write documentation strings for class attributes |
from __future__ import annotations
_INF = float("inf")
def min_cost(cost: list[list[int]]) -> int:
length = len(cost)
dist = [_INF] * length
dist[0] = 0
for i in range(length):
for j in range(i + 1, length):
dist[j] = min(dist[j], dist[i] + cost[i][j])
return dist[length -... | --- +++ @@ -1,3 +1,16 @@+"""
+Minimum Cost Path
+
+Find the minimum cost to travel from station 0 to station N-1 given
+a cost matrix where cost[i][j] is the price of going from station i
+to station j (for i < j).
+
+Reference: https://en.wikipedia.org/wiki/Shortest_path_problem
+
+Complexity:
+ Time: O(n^2)
+ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/min_cost_path.py |
Include argument descriptions in docstrings |
from __future__ import annotations
def is_anagram(s: str, t: str) -> bool:
freq_s: dict[str, int] = {}
freq_t: dict[str, int] = {}
for char in s:
freq_s[char] = freq_s.get(char, 0) + 1
for char in t:
freq_t[char] = freq_t.get(char, 0) + 1
return freq_s == freq_t | --- +++ @@ -1,12 +1,39 @@+"""
+Is Anagram
+
+Determine whether two strings are anagrams of each other by comparing
+character frequency maps.
+
+Reference: https://leetcode.com/problems/valid-anagram/description/
+
+Complexity:
+ Time: O(n)
+ Space: O(n)
+"""
from __future__ import annotations
def is_ana... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/map/is_anagram.py |
Generate missing documentation strings |
from __future__ import annotations
def is_isomorphic(s: str, t: str) -> bool:
if len(s) != len(t):
return False
mapping: dict[str, str] = {}
mapped_values: set[str] = set()
for i in range(len(s)):
if s[i] not in mapping:
if t[i] in mapped_values:
return Fal... | --- +++ @@ -1,8 +1,36 @@+"""
+Isomorphic Strings
+
+Determine if two strings are isomorphic. Two strings are isomorphic if
+characters in s can be mapped to characters in t while preserving order,
+with a one-to-one mapping.
+
+Reference: https://leetcode.com/problems/isomorphic-strings/description/
+
+Complexity:
+ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/map/is_isomorphic.py |
Write docstrings for data processing functions |
from __future__ import annotations
class Node:
def __init__(self, val: object = None) -> None:
self.val = val
self.next: Node | None = None
def remove_dups(head: Node | None) -> None:
seen: set[object] = set()
prev = Node()
while head:
if head.val in seen:
prev.n... | --- +++ @@ -1,3 +1,16 @@+"""
+Remove Duplicates from Linked List
+
+Remove duplicate values from an unsorted linked list. Two approaches are
+provided: hash-set-based (O(n) time, O(n) space) and runner technique
+(O(n^2) time, O(1) space).
+
+Reference: https://en.wikipedia.org/wiki/Linked_list
+
+Complexity (hash set)... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/remove_duplicates.py |
Add docstrings explaining edge cases |
from __future__ import annotations
def is_palindrome(head: object | None) -> bool:
if not head:
return True
fast, slow = head.next, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
second = slow.next
slow.next = None
node = None
while second:
... | --- +++ @@ -1,8 +1,32 @@+"""
+Palindrome Linked List
+
+Determine whether a singly linked list is a palindrome. Three approaches are
+provided: reverse-half, stack-based, and dictionary-based.
+
+Reference: https://leetcode.com/problems/palindrome-linked-list/
+
+Complexity (reverse-half):
+ Time: O(n)
+ Space: ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/linked_list/is_palindrome.py |
Create Google-style docstrings for my code |
from __future__ import annotations
def max_common_sub_string(s1: str, s2: str) -> str:
char_index = {s2[i]: i for i in range(len(s2))}
max_length = 0
best_substring = ""
i = 0
while i < len(s1):
if s1[i] in char_index:
j = char_index[s1[i]]
k = i
while ... | --- +++ @@ -1,8 +1,36 @@+"""
+Longest Common Substring
+
+Given two strings where the second contains all distinct characters,
+find the longest common substring using index mapping.
+
+Reference: https://en.wikipedia.org/wiki/Longest_common_substring_problem
+
+Complexity:
+ Time: O(n log n) expected, O(n * m) wor... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/map/longest_common_subsequence.py |
Document all endpoints with docstrings |
from __future__ import annotations
import random
class RandomizedSet:
def __init__(self) -> None:
self.nums: list[int] = []
self.idxs: dict[int, int] = {}
def insert(self, val: int) -> bool:
if val not in self.idxs:
self.nums.append(val)
self.idxs[val] = len... | --- +++ @@ -1,3 +1,16 @@+"""
+Randomized Set
+
+Design a data structure that supports insert, remove, and getRandom
+in average O(1) time. Uses a list for random access and a dictionary
+for O(1) lookup/removal.
+
+Reference: https://leetcode.com/problems/insert-delete-getrandom-o1/
+
+Complexity:
+ Time: O(1) aver... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/map/randomized_set.py |
Document functions with clear intent |
from __future__ import annotations
def longest_palindromic_subsequence(s: str) -> int:
length = len(s)
previous_row = [0] * length
current_row = [0] * length
longest_length = 0
for end in range(length):
for start in range(end + 1):
if end - start <= 1:
if s[st... | --- +++ @@ -1,8 +1,34 @@+"""
+Longest Palindromic Substring
+
+Find the length of the longest palindromic substring using dynamic
+programming with two rolling arrays.
+
+Reference: https://en.wikipedia.org/wiki/Longest_palindromic_substring
+
+Complexity:
+ Time: O(n^2)
+ Space: O(n)
+"""
from __future__ imp... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/map/longest_palindromic_subsequence.py |
Can you add docstrings to this Python file? |
from __future__ import annotations
def combination(n: int, r: int) -> int:
if n == r or r == 0:
return 1
return combination(n - 1, r - 1) + combination(n - 1, r)
def combination_memo(n: int, r: int) -> int:
memo: dict[tuple[int, int], int] = {}
def _recur(n: int, r: int) -> int:
if... | --- +++ @@ -1,14 +1,54 @@+"""
+Combinations (nCr)
+
+Calculate the number of ways to choose r items from n items (binomial
+coefficient) using recursive and memoized approaches.
+
+Reference: https://en.wikipedia.org/wiki/Combination
+
+Complexity:
+ Time: O(2^n) naive recursive, O(n*r) memoized
+ Space: O(n) re... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/combination.py |
Add verbose docstrings with examples |
from __future__ import annotations
def max_subarray(array: list[int]) -> int:
max_so_far = max_now = array[0]
for i in range(1, len(array)):
max_now = max(array[i], max_now + array[i])
max_so_far = max(max_so_far, max_now)
return max_so_far | --- +++ @@ -1,10 +1,33 @@+"""
+Maximum Subarray (Kadane's Algorithm)
+
+Find the contiguous subarray with the largest sum.
+
+Reference: https://en.wikipedia.org/wiki/Maximum_subarray_problem
+
+Complexity:
+ Time: O(n)
+ Space: O(1)
+"""
from __future__ import annotations
def max_subarray(array: list[in... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/dynamic_programming/max_subarray.py |
Generate helpful docstrings for debugging |
from __future__ import annotations
def word_pattern(pattern: str, string: str) -> bool:
mapping: dict[str, str] = {}
mapped_values: set[str] = set()
words = string.split()
if len(words) != len(pattern):
return False
for i in range(len(pattern)):
if pattern[i] not in mapping:
... | --- +++ @@ -1,8 +1,35 @@+"""
+Word Pattern
+
+Given a pattern and a string, determine if the string follows the same
+pattern via a bijection between pattern letters and words.
+
+Reference: https://leetcode.com/problems/word-pattern/description/
+
+Complexity:
+ Time: O(n)
+ Space: O(n)
+"""
from __future__ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/map/word_pattern.py |
Create Google-style docstrings for my code |
from __future__ import annotations
import copy
import math
import queue
def maximum_flow_bfs(adjacency_matrix: list[list[int]]) -> int:
new_array = copy.deepcopy(adjacency_matrix)
total = 0
while True:
min_flow = math.inf
visited = [0] * len(new_array)
path = [0] * len(new_array... | --- +++ @@ -1,3 +1,15 @@+"""
+Maximum Flow via BFS
+
+Computes maximum flow in a network represented as an adjacency matrix,
+using BFS to find augmenting paths.
+
+Reference: https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm
+
+Complexity:
+ Time: O(V * E^2)
+ Space: O(V^2)
+"""
from __future__ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/maximum_flow_bfs.py |
Write reusable docstrings |
from __future__ import annotations
import string
def int_to_base(num: int, base: int) -> str:
is_negative = False
if num == 0:
return "0"
if num < 0:
is_negative = True
num *= -1
digit = string.digits + string.ascii_uppercase
res = ""
while num > 0:
res += dig... | --- +++ @@ -1,3 +1,15 @@+"""
+Integer Base Conversion
+
+Convert integers between arbitrary bases (2-36). Supports conversion from
+integer to string representation in a given base, and vice versa.
+
+Reference: https://en.wikipedia.org/wiki/Positional_notation
+
+Complexity:
+ Time: O(log_base(num)) for both direc... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/base_conversion.py |
Write reusable docstrings |
from __future__ import annotations
def extended_gcd(num1: int, num2: int) -> tuple[int, int, int]:
old_s, s = 1, 0
old_t, t = 0, 1
old_r, r = num1, num2
while r != 0:
quotient = old_r / r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t ... | --- +++ @@ -1,8 +1,35 @@+"""
+Extended Euclidean Algorithm
+
+Find coefficients s and t (Bezout's identity) such that:
+num1 * s + num2 * t = gcd(num1, num2).
+
+Reference: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
+
+Complexity:
+ Time: O(log(min(num1, num2)))
+ Space: O(1)
+"""
from __futur... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/extended_gcd.py |
Document all endpoints with docstrings |
from __future__ import annotations
import math
def _l2_distance(vec: list[float]) -> float:
norm = 0.0
for element in vec:
norm += element * element
norm = math.sqrt(norm)
return norm
def cosine_similarity(vec1: list[float], vec2: list[float]) -> float:
if len(vec1) != len(vec2):
... | --- +++ @@ -1,3 +1,16 @@+"""
+Cosine Similarity
+
+Calculate the cosine similarity between two vectors, which measures the
+cosine of the angle between them. Values range from -1 (opposite) to 1
+(identical direction).
+
+Reference: https://en.wikipedia.org/wiki/Cosine_similarity
+
+Complexity:
+ Time: O(n)
+ Sp... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/cosine_similarity.py |
Generate consistent docstrings |
from __future__ import annotations
def decimal_to_binary_util(val: str) -> str:
bits = [128, 64, 32, 16, 8, 4, 2, 1]
val_int = int(val)
binary_rep = ""
for bit in bits:
if val_int >= bit:
binary_rep += str(1)
val_int -= bit
else:
binary_rep += str(0... | --- +++ @@ -1,8 +1,32 @@+"""
+Decimal to Binary IP Conversion
+
+Convert an IP address from dotted-decimal notation to its binary
+representation.
+
+Reference: https://en.wikipedia.org/wiki/IP_address
+
+Complexity:
+ Time: O(1) (fixed 4 octets, 8 bits each)
+ Space: O(1)
+"""
from __future__ import annotati... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/decimal_to_binary_ip.py |
Write docstrings for utility functions |
from __future__ import annotations
from cmath import exp, pi
def fft(x: list[complex]) -> list[complex]:
n = len(x)
if n == 1:
return x
even = fft(x[0::2])
odd = fft(x[1::2])
y = [0 for _ in range(n)]
for k in range(n // 2):
q = exp(-2j * pi * k / n) * odd[k]
y[k] =... | --- +++ @@ -1,3 +1,15 @@+"""
+Fast Fourier Transform (Cooley-Tukey)
+
+Compute the Discrete Fourier Transform of a sequence using the Cooley-Tukey
+radix-2 decimation-in-time algorithm. Input length must be a power of 2.
+
+Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm
+
+Complexity:
+ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/fft.py |
Add documentation for all methods |
from __future__ import annotations
def factorial(n: int, mod: int | None = None) -> int:
if not (isinstance(n, int) and n >= 0):
raise ValueError("'n' must be a non-negative integer.")
if mod is not None and not (isinstance(mod, int) and mod > 0):
raise ValueError("'mod' must be a positive in... | --- +++ @@ -1,8 +1,38 @@+"""
+Factorial
+
+Compute the factorial of a non-negative integer, with optional modular
+arithmetic support.
+
+Reference: https://en.wikipedia.org/wiki/Factorial
+
+Complexity:
+ Time: O(n)
+ Space: O(1) iterative, O(n) recursive
+"""
from __future__ import annotations
def fact... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/factorial.py |
Generate docstrings for this script |
from __future__ import annotations
from math import sqrt
def distance_between_two_points(x1: float, y1: float, x2: float, y2: float) -> float:
return sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) | --- +++ @@ -1,3 +1,15 @@+"""
+Distance Between Two Points in 2D Space
+
+Calculate the Euclidean distance between two points using the distance
+formula derived from the Pythagorean theorem.
+
+Reference: https://en.wikipedia.org/wiki/Euclidean_distance
+
+Complexity:
+ Time: O(1)
+ Space: O(1)
+"""
from __fu... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/distance_between_two_points.py |
Write docstrings that follow conventions |
from __future__ import annotations
import math
import secrets
def _prime_check(num: int) -> bool:
if num <= 1:
return False
if num == 2 or num == 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
j = 5
while j * j <= num:
if num % j == 0 or num % (j + 2... | --- +++ @@ -1,3 +1,16 @@+"""
+Diffie-Hellman Key Exchange
+
+Implements the Diffie-Hellman key exchange protocol, which enables two parties
+to establish a shared secret over an insecure channel using discrete
+logarithm properties.
+
+Reference: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
+
+Comp... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/diffie_hellman_key_exchange.py |
Add docstrings that explain inputs and outputs |
from __future__ import annotations
import math
def _find_order(a: int, n: int) -> int:
if (a == 1) & (n == 1):
return 1
if math.gcd(a, n) != 1:
return -1
for i in range(1, n):
if pow(a, i) % n == 1:
return i
return -1
def _euler_totient(n: int) -> int:
resul... | --- +++ @@ -1,3 +1,16 @@+"""
+Primitive Root Finder
+
+Find all primitive roots of a positive integer n. A primitive root modulo n
+is an integer whose multiplicative order modulo n equals Euler's totient
+of n.
+
+Reference: https://en.wikipedia.org/wiki/Primitive_root_modulo_n
+
+Complexity:
+ Time: O(n^2 log n)
... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/find_primitive_root_simple.py |
Generate consistent docstrings |
from __future__ import annotations
import math
def find_order(a: int, n: int) -> int:
if (a == 1) & (n == 1):
return 1
if math.gcd(a, n) != 1:
return -1
for i in range(1, n):
if pow(a, i) % n == 1:
return i
return -1 | --- +++ @@ -1,3 +1,15 @@+"""
+Multiplicative Order
+
+Find the multiplicative order of a modulo n, which is the smallest positive
+integer k such that a^k = 1 (mod n). Requires gcd(a, n) = 1.
+
+Reference: https://en.wikipedia.org/wiki/Multiplicative_order
+
+Complexity:
+ Time: O(n log n)
+ Space: O(1)
+"""
... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/find_order_simple.py |
Write docstrings describing functionality |
from __future__ import annotations
def _is_prime(n: int) -> bool:
if n < 2:
return False
if n < 4:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return Tr... | --- +++ @@ -1,8 +1,29 @@+"""
+Goldbach's Conjecture
+
+Every even integer greater than 2 can be expressed as the sum of two primes.
+This module provides a function to find such a pair of primes and a helper
+to verify the conjecture over a range.
+
+Reference: https://en.wikipedia.org/wiki/Goldbach%27s_conjecture
+
+C... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/goldbach.py |
Create structured documentation for my script |
from __future__ import annotations
def _find_factorial(n: int) -> int:
fact = 1
while n != 0:
fact *= n
n -= 1
return fact
def krishnamurthy_number(n: int) -> bool:
if n == 0:
return False
sum_of_digits = 0
temp = n
while temp != 0:
sum_of_digits += _fin... | --- +++ @@ -1,8 +1,28 @@+"""
+Krishnamurthy Number
+
+A Krishnamurthy number is a number whose sum of the factorials of its digits
+equals the number itself (e.g., 145 = 1! + 4! + 5!).
+
+Reference: https://en.wikipedia.org/wiki/Factorion
+
+Complexity:
+ Time: O(d * m) where d is number of digits and m is max digi... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/krishnamurthy_number.py |
Add docstrings to incomplete code |
from __future__ import annotations
def is_strobogrammatic(num: str) -> bool:
comb = "00 11 88 69 96"
i = 0
j = len(num) - 1
while i <= j:
if comb.find(num[i] + num[j]) == -1:
return False
i += 1
j -= 1
return True
def is_strobogrammatic2(num: str) -> bool:
... | --- +++ @@ -1,8 +1,34 @@+"""
+Strobogrammatic Number Check
+
+Determine whether a number (as a string) is strobogrammatic, meaning it
+looks the same when rotated 180 degrees.
+
+Reference: https://en.wikipedia.org/wiki/Strobogrammatic_number
+
+Complexity:
+ Time: O(n) where n is the length of the number string
+ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/is_strobogrammatic.py |
Add standardized docstrings across the file |
from __future__ import annotations
def euler_totient(n: int) -> int:
result = n
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
while n % i == 0:
n //= i
result -= result // i
if n > 1:
result -= result // n
return result | --- +++ @@ -1,8 +1,34 @@+"""
+Euler's Totient Function
+
+Compute Euler's totient function phi(n), which counts the number of integers
+from 1 to n inclusive that are coprime to n.
+
+Reference: https://en.wikipedia.org/wiki/Euler%27s_totient_function
+
+Complexity:
+ Time: O(sqrt(n))
+ Space: O(1)
+"""
from ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/euler_totient.py |
Insert docstrings into my code |
from __future__ import annotations
def next_bigger(num: int) -> int:
digits = [int(i) for i in str(num)]
idx = len(digits) - 1
while idx >= 1 and digits[idx - 1] >= digits[idx]:
idx -= 1
if idx == 0:
return -1
pivot = digits[idx - 1]
swap_idx = len(digits) - 1
while pi... | --- +++ @@ -1,8 +1,35 @@+"""
+Next Bigger Number with Same Digits
+
+Given a number, find the next higher number that uses the exact same set of
+digits. This is equivalent to finding the next permutation.
+
+Reference: https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
+
+Complexity:
+ Time... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/next_bigger.py |
Generate docstrings with examples |
from __future__ import annotations
from collections.abc import Iterable
from fractions import Fraction
from functools import reduce
from numbers import Rational
class Monomial:
def __init__(
self, variables: dict[int, int], coeff: int | float | Fraction | None = None
) -> None:
self.variabl... | --- +++ @@ -1,3 +1,16 @@+"""
+Polynomial and Monomial Arithmetic
+
+A symbolic algebra system for polynomials and monomials supporting addition,
+subtraction, multiplication, division, substitution, and polynomial long
+division with Fraction-based exact arithmetic.
+
+Reference: https://en.wikipedia.org/wiki/Polynomia... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/polynomial.py |
Write docstrings including parameters and return values |
from __future__ import annotations
def gcd(a: int, b: int) -> int:
a_int = isinstance(a, int)
b_int = isinstance(b, int)
a = abs(a)
b = abs(b)
if not (a_int or b_int):
raise ValueError("Input arguments are not integers")
if (a == 0) or (b == 0):
raise ValueError("One or more ... | --- +++ @@ -1,8 +1,38 @@+"""
+Greatest Common Divisor and Least Common Multiple
+
+Compute the GCD and LCM of two integers using Euclid's algorithm and
+a bitwise variant.
+
+Reference: https://en.wikipedia.org/wiki/Euclidean_algorithm
+
+Complexity:
+ Time: O(log(min(a, b))) for gcd, O(log(min(a, b))) for lcm
+ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/gcd.py |
Help me write clear docstrings |
from __future__ import annotations
def hailstone(n: int) -> list[int]:
sequence = [n]
while n > 1:
n = 3 * n + 1 if n % 2 != 0 else int(n / 2)
sequence.append(n)
return sequence | --- +++ @@ -1,10 +1,36 @@+"""
+Hailstone Sequence (Collatz Conjecture)
+
+Generate the hailstone sequence starting from n: if n is even, next is n/2;
+if n is odd, next is 3n + 1. The sequence ends when it reaches 1.
+
+Reference: https://en.wikipedia.org/wiki/Collatz_conjecture
+
+Complexity:
+ Time: O(unknown) - ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/hailstone.py |
Include argument descriptions in docstrings |
from __future__ import annotations
def find_next_square(sq: float) -> float:
root = sq**0.5
if root.is_integer():
return (root + 1) ** 2
return -1
def find_next_square2(sq: float) -> float:
root = sq**0.5
return -1 if root % 1 else (root + 1) ** 2 | --- +++ @@ -1,8 +1,34 @@+"""
+Next Perfect Square
+
+Given a number, find the next perfect square if the input is itself a perfect
+square. Otherwise, return -1.
+
+Reference: https://en.wikipedia.org/wiki/Square_number
+
+Complexity:
+ Time: O(1)
+ Space: O(1)
+"""
from __future__ import annotations
def... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/next_perfect_square.py |
Generate docstrings for exported functions |
from __future__ import annotations
def gen_strobogrammatic(n: int) -> list[str]:
return _helper(n, n)
def _helper(n: int, length: int) -> list[str]:
if n == 0:
return [""]
if n == 1:
return ["1", "0", "8"]
middles = _helper(n - 2, length)
result = []
for middle in middles:
... | --- +++ @@ -1,12 +1,45 @@+"""
+Generate Strobogrammatic Numbers
+
+A strobogrammatic number looks the same when rotated 180 degrees. Generate
+all strobogrammatic numbers of a given length or count them within a range.
+
+Reference: https://en.wikipedia.org/wiki/Strobogrammatic_number
+
+Complexity:
+ Time: O(5^(n/... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/generate_strobogrammtic.py |
Write docstrings describing each step |
from __future__ import annotations
def magic_number(n: int) -> bool:
total_sum = 0
while n > 0 or total_sum > 9:
if n == 0:
n = total_sum
total_sum = 0
total_sum += n % 10
n //= 10
return total_sum == 1 | --- +++ @@ -1,8 +1,34 @@+"""
+Magic Number
+
+A magic number is a number where recursively summing its digits eventually
+yields 1. For example, 199 -> 1+9+9=19 -> 1+9=10 -> 1+0=1.
+
+Reference: https://en.wikipedia.org/wiki/Digital_root
+
+Complexity:
+ Time: O(log n) amortized
+ Space: O(1)
+"""
from __futu... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/magic_number.py |
Replace inline comments with docstrings |
from __future__ import annotations
import math
def linear_regression(x: list[float], y: list[float]) -> tuple[float, float]:
n = len(x)
if n != len(y) or n < 2:
msg = "x and y must have at least 2 equal-length elements"
raise ValueError(msg)
sum_x = sum(x)
sum_y = sum(y)
sum_xy =... | --- +++ @@ -1,3 +1,10 @@+"""Simple linear regression — fit a line to (x, y) data.
+
+Computes the ordinary least-squares regression line y = mx + b
+without external libraries.
+
+Inspired by PR #871 (MakanFar).
+"""
from __future__ import annotations
@@ -5,6 +12,14 @@
def linear_regression(x: list[float], y: ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/linear_regression.py |
Create Google-style docstrings for my code |
from __future__ import annotations
import math
def num_digits(n: int) -> int:
n = abs(n)
if n == 0:
return 1
return int(math.log10(n)) + 1 | --- +++ @@ -1,3 +1,15 @@+"""
+Number of Digits
+
+Count the number of digits in an integer using logarithmic computation
+for O(1) time complexity.
+
+Reference: https://en.wikipedia.org/wiki/Logarithm
+
+Complexity:
+ Time: O(1)
+ Space: O(1)
+"""
from __future__ import annotations
@@ -5,7 +17,23 @@
de... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/num_digits.py |
Add documentation for all methods |
from __future__ import annotations
def modular_exponential(base: int, exponent: int, mod: int) -> int:
if exponent < 0:
raise ValueError("Exponent must be positive.")
base %= mod
result = 1
while exponent > 0:
if exponent & 1:
result = (result * base) % mod
expone... | --- +++ @@ -1,8 +1,37 @@+"""
+Modular Exponentiation
+
+Compute (base ^ exponent) % mod efficiently using binary exponentiation
+(repeated squaring).
+
+Reference: https://en.wikipedia.org/wiki/Modular_exponentiation
+
+Complexity:
+ Time: O(log exponent)
+ Space: O(1)
+"""
from __future__ import annotations
... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/modular_exponential.py |
Generate consistent documentation across files |
from __future__ import annotations
def manhattan_distance(a: tuple[float, ...], b: tuple[float, ...]) -> float:
return sum(abs(x - y) for x, y in zip(a, b, strict=False)) | --- +++ @@ -1,6 +1,22 @@+"""Manhattan distance — L1 distance between two points.
+
+Also known as taxicab distance or city-block distance, it is the sum
+of absolute differences of coordinates.
+
+Inspired by PR #877 (ChinZhengSheng).
+"""
from __future__ import annotations
def manhattan_distance(a: tuple[float... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/manhattan_distance.py |
Add docstrings for production code |
from __future__ import annotations
import math
def num_perfect_squares(number: int) -> int:
if int(math.sqrt(number)) ** 2 == number:
return 1
while number > 0 and number % 4 == 0:
number /= 4
if number % 8 == 7:
return 4
for i in range(1, int(math.sqrt(number)) + 1):
... | --- +++ @@ -1,3 +1,15 @@+"""
+Minimum Perfect Squares Sum
+
+Determine the minimum number of perfect squares that sum to a given integer.
+By Lagrange's four-square theorem, the answer is always between 1 and 4.
+
+Reference: https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem
+
+Complexity:
+ Time: O(sq... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/num_perfect_squares.py |
Document functions with detailed explanations |
from __future__ import annotations
def prime_check(n: int) -> bool:
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
j = 5
while j * j <= n:
if n % j == 0 or n % (j + 2) == 0:
return False
j += 6... | --- +++ @@ -1,8 +1,34 @@+"""
+Primality Test
+
+Check whether a given integer is prime using trial division with 6k +/- 1
+optimization.
+
+Reference: https://en.wikipedia.org/wiki/Primality_test
+
+Complexity:
+ Time: O(sqrt(n))
+ Space: O(1)
+"""
from __future__ import annotations
def prime_check(n: in... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/prime_check.py |
Document helper functions with docstrings |
from __future__ import annotations
from collections import deque
def maze_search(maze: list[list[int]]) -> int:
blocked, allowed = 0, 1
unvisited, visited = 0, 1
initial_x, initial_y = 0, 0
if maze[initial_x][initial_y] == blocked:
return -1
directions = [(0, -1), (0, 1), (-1, 0), (1,... | --- +++ @@ -1,3 +1,14 @@+"""
+Maze Search (BFS)
+
+Find the minimum number of steps from the top-left corner to the
+bottom-right corner of a grid. Only cells with value 1 may be traversed.
+Returns -1 if no path exists.
+
+Complexity:
+ Time: O(M * N)
+ Space: O(M * N)
+"""
from __future__ import annotation... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/maze_search_bfs.py |
Generate docstrings with examples |
from __future__ import annotations
def get_primes(n: int) -> list[int]:
if n <= 0:
raise ValueError("'n' must be a positive integer.")
sieve_size = (n // 2 - 1) if n % 2 == 0 else (n // 2)
sieve = [True for _ in range(sieve_size)]
primes: list[int] = []
if n >= 2:
primes.append(2)... | --- +++ @@ -1,8 +1,35 @@+"""
+Sieve of Eratosthenes
+
+Generate all prime numbers less than n using an optimized sieve that skips
+even numbers.
+
+Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
+
+Complexity:
+ Time: O(n log log n)
+ Space: O(n)
+"""
from __future__ import annotations
de... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/primes_sieve_of_eratosthenes.py |
Generate docstrings with parameter types |
from __future__ import annotations
def find_nth_digit(n: int) -> int:
length = 1
count = 9
start = 1
while n > length * count:
n -= length * count
length += 1
count *= 10
start *= 10
start += (n - 1) / length
s = str(start)
return int(s[(n - 1) % length]) | --- +++ @@ -1,8 +1,32 @@+"""
+Find the Nth Digit
+
+Find the nth digit in the infinite sequence 1, 2, 3, ..., 9, 10, 11, 12, ...
+by determining which number contains it and extracting the specific digit.
+
+Reference: https://en.wikipedia.org/wiki/Positional_notation
+
+Complexity:
+ Time: O(log n)
+ Space: O(l... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/nth_digit.py |
Create Google-style docstrings for my code |
from __future__ import annotations
def _extended_gcd(a: int, b: int) -> tuple[int, int, int]:
old_s, s = 1, 0
old_t, t = 0, 1
old_r, r = a, b
while r != 0:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t... | --- +++ @@ -1,8 +1,29 @@+"""
+Modular Multiplicative Inverse
+
+Find x such that a * x = 1 (mod m) using the Extended Euclidean Algorithm.
+Requires a and m to be coprime.
+
+Reference: https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
+
+Complexity:
+ Time: O(log(min(a, m)))
+ Space: O(1)
+"""
fro... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/modular_inverse.py |
Add standardized docstrings across the file |
from __future__ import annotations
def power(a: int, n: int, mod: int | None = None) -> int:
ans = 1
while n:
if n & 1:
ans = ans * a
a = a * a
if mod:
ans %= mod
a %= mod
n >>= 1
return ans
def power_recur(a: int, n: int, mod: int | N... | --- +++ @@ -1,8 +1,36 @@+"""
+Binary Exponentiation
+
+Compute a^n efficiently using binary exponentiation (exponentiation by
+squaring), with optional modular arithmetic.
+
+Reference: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
+
+Complexity:
+ Time: O(log n)
+ Space: O(1) iterative, O(log n) recu... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/power.py |
Generate descriptive docstrings automatically |
from __future__ import annotations
import math
def cholesky_decomposition(matrix: list[list[float]]) -> list[list[float]] | None:
size = len(matrix)
for row in matrix:
if len(row) != size:
return None
result = [[0.0] * size for _ in range(size)]
for j in range(size):
diag... | --- +++ @@ -1,3 +1,16 @@+"""
+Cholesky Matrix Decomposition
+
+Decompose a Hermitian positive-definite matrix A into a lower-triangular
+matrix V such that V * V^T = A. Mainly used for numerical solution of
+linear equations Ax = b.
+
+Reference: https://en.wikipedia.org/wiki/Cholesky_decomposition
+
+Complexity:
+ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/cholesky_matrix_decomposition.py |
Add missing documentation to my Python functions |
from __future__ import annotations
def recursive_binomial_coefficient(n: int, k: int) -> int:
if k > n:
raise ValueError("Invalid Inputs, ensure that n >= k")
if k == 0 or n == k:
return 1
if k > n / 2:
return recursive_binomial_coefficient(n, n - k)
return int((n / k) * recur... | --- +++ @@ -1,12 +1,42 @@+"""
+Recursive Binomial Coefficient
+
+Calculate the binomial coefficient C(n, k) using a recursive formula with
+the identity C(n, k) = (n/k) * C(n-1, k-1).
+
+Reference: https://en.wikipedia.org/wiki/Binomial_coefficient
+
+Complexity:
+ Time: O(k)
+ Space: O(k) recursive stack
+"""
... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/recursive_binomial_coefficient.py |
Provide docstrings following PEP 257 |
from __future__ import annotations
def sum_dig_pow(low: int, high: int) -> list[int]:
result = []
for number in range(low, high + 1):
exponent = 1
summation = 0
number_as_string = str(number)
tokens = list(map(int, number_as_string))
for k in tokens:
sum... | --- +++ @@ -1,8 +1,35 @@+"""
+Summing Digits Power
+
+Find all integers in a range where each digit raised to its positional power
+(1-indexed) sums to the number itself (e.g., 89 = 8^1 + 9^2).
+
+Reference: https://en.wikipedia.org/wiki/Perfect_digit-to-digit_invariant
+
+Complexity:
+ Time: O((high - low) * d) wh... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/summing_digits.py |
Improve documentation using docstrings |
from __future__ import annotations
import secrets
def is_prime(n: int, k: int) -> bool:
def _pow2_factor(num: int) -> tuple[int, int]:
power = 0
while num % 2 == 0:
num //= 2
power += 1
return power, num
def _valid_witness(a: int) -> bool:
x = pow(in... | --- +++ @@ -1,3 +1,16 @@+"""
+Rabin-Miller Primality Test
+
+A probabilistic primality test where returning False guarantees the number
+is composite, and returning True means the number is probably prime with
+a 4^(-k) chance of error.
+
+Reference: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
+
+... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/rabin_miller.py |
Add documentation for all methods |
from __future__ import annotations
def max_killed_enemies(grid: list[list[str]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
max_killed = 0
row_enemies, col_enemies = 0, [0] * cols
for i in range(rows):
for j in range(cols):
if j == 0 or grid[i][... | --- +++ @@ -1,8 +1,35 @@+"""
+Bomb Enemy
+
+Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0'
+(the number zero). Return the maximum enemies you can kill using one bomb.
+The bomb kills all the enemies in the same row and column from the planted
+point until it hits the wall since it is too str... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/bomb_enemy.py |
Annotate my code with docstrings |
from __future__ import annotations
from math import pi
def surface_area_of_torus(major_radius: float, minor_radius: float) -> float:
if major_radius < 0 or minor_radius < 0:
raise ValueError("Radii must be non-negative")
return 4 * pi**2 * major_radius * minor_radius | --- +++ @@ -1,3 +1,15 @@+"""
+Surface Area of a Torus
+
+Calculate the surface area of a torus given its major and minor radii
+using the formula A = 4 * pi^2 * R * r.
+
+Reference: https://en.wikipedia.org/wiki/Torus
+
+Complexity:
+ Time: O(1)
+ Space: O(1)
+"""
from __future__ import annotations
@@ -5,7 ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/surface_area_of_torus.py |
Provide docstrings following PEP 257 |
from __future__ import annotations
def square_root(n: float, epsilon: float = 0.001) -> float:
guess = n / 2
while abs(guess * guess - n) > epsilon:
guess = (guess + (n / guess)) / 2
return guess | --- +++ @@ -1,11 +1,36 @@+"""
+Square Root by Newton's Method
+
+Compute the square root of a positive number using Newton's method
+(Babylonian method) with a configurable precision factor.
+
+Reference: https://en.wikipedia.org/wiki/Newton%27s_method#Square_root
+
+Complexity:
+ Time: O(log(1/epsilon)) iterations... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/sqrt_precision_factor.py |
Improve documentation using docstrings |
from __future__ import annotations
def vector_to_index_value_list(
vector: list[float],
) -> list[tuple[int, float]]:
return [(i, v) for i, v in enumerate(vector) if v != 0.0]
def dot_product(
iv_list1: list[tuple[int, float]],
iv_list2: list[tuple[int, float]],
) -> float:
product = 0
p1 =... | --- +++ @@ -1,3 +1,15 @@+"""
+Sparse Dot Vector
+
+Compute the dot product of two large sparse vectors efficiently by
+converting them to index-value pair representations and merging.
+
+Reference: https://leetcode.com/problems/dot-product-of-two-sparse-vectors/
+
+Complexity:
+ Time: O(n) for conversion, O(k) for ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/sparse_dot_vector.py |
Generate docstrings for this script |
from __future__ import annotations
from fractions import Fraction
from algorithms.math.gcd import lcm
from algorithms.math.polynomial import Monomial, Polynomial
def cycle_product(m1: Monomial, m2: Monomial) -> Monomial:
assert isinstance(m1, Monomial) and isinstance(m2, Monomial)
a_vars = m1.variables
... | --- +++ @@ -1,3 +1,16 @@+"""
+Symmetry Group Cycle Index
+
+Compute the cycle index polynomial of the symmetric group S_n and use it
+to count distinct configurations of grids under row/column permutations
+via Burnside's lemma.
+
+Reference: https://en.wikipedia.org/wiki/Cycle_index#Symmetric_group_Sn
+
+Complexity:
+... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/symmetry_group_cycle_index.py |
Generate descriptive docstrings automatically |
from __future__ import annotations
import secrets
def _extended_gcd(a: int, b: int) -> tuple[int, int, int]:
old_r, r = a, b
old_s, s = 1, 0
old_t, t = 0, 1
while r != 0:
q = old_r // r
old_r, r = r, old_r - q * r
old_s, s = s, old_s - q * s
old_t, t = t, old_t - q * ... | --- +++ @@ -1,3 +1,15 @@+"""
+RSA Encryption Algorithm
+
+Implements RSA key generation, encryption, and decryption. RSA uses separate
+public and private keys where ((x^e)^d) % n == x % n.
+
+Reference: https://en.wikipedia.org/wiki/RSA_(cryptosystem)
+
+Complexity:
+ Time: O(k^3) for key generation (k = bit lengt... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/rsa.py |
Write docstrings for algorithm functions |
from __future__ import annotations
def rotate(mat: list[list[int]]) -> list[list[int]]:
if not mat:
return mat
mat.reverse()
for i in range(len(mat)):
for j in range(i):
mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
return mat | --- +++ @@ -1,12 +1,36 @@+"""
+Rotate Image
+
+Rotate an n x n 2D matrix representing an image by 90 degrees clockwise,
+in-place. First reverse the rows top-to-bottom, then transpose.
+
+Reference: https://leetcode.com/problems/rotate-image/
+
+Complexity:
+ Time: O(n^2)
+ Space: O(1)
+"""
from __future__ im... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/rotate_image.py |
Create structured documentation for my script |
from __future__ import annotations
def rotate_clockwise(matrix: list[list[int]]) -> list[list[int]]:
result: list[list[int]] = []
for row in reversed(matrix):
for i, elem in enumerate(row):
try:
result[i].append(elem)
except IndexError:
result.i... | --- +++ @@ -1,8 +1,33 @@+"""
+Copy Transform
+
+Rotate and invert a matrix by creating transformed copies.
+Provides clockwise rotation, counterclockwise rotation, top-left
+inversion (transpose), and bottom-left inversion (anti-transpose).
+
+Reference: https://en.wikipedia.org/wiki/Transpose
+
+Complexity:
+ Time:... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/copy_transform.py |
Document all endpoints with docstrings |
from __future__ import annotations
def crout_matrix_decomposition(
matrix: list[list[float]],
) -> tuple[list[list[float]], list[list[float]]]:
size = len(matrix)
lower = [[0.0] * size for _ in range(size)]
upper = [[0.0] * size for _ in range(size)]
for j in range(size):
upper[j][j] = 1.... | --- +++ @@ -1,3 +1,17 @@+"""
+Crout Matrix Decomposition
+
+Decompose a matrix A into lower-triangular matrix L and upper-triangular
+matrix U such that L * U = A. L has non-zero elements only on and below
+the diagonal; U has non-zero elements only on and above the diagonal
+with ones on the diagonal.
+
+Reference: ht... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/crout_matrix_decomposition.py |
Document this script properly |
from __future__ import annotations
def reconstruct_queue(people: list[list[int]]) -> list[list[int]]:
queue: list[list[int]] = []
people.sort(key=lambda x: (-x[0], x[1]))
for height, count in people:
queue.insert(count, [height, count])
return queue | --- +++ @@ -1,10 +1,35 @@+"""
+Reconstruct Queue by Height
+
+Given a list of people described by (height, k) pairs where k is the
+number of taller-or-equal people in front, reconstruct the queue by
+sorting and inserting.
+
+Reference: https://leetcode.com/problems/queue-reconstruction-by-height/
+
+Complexity:
+ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/queue/reconstruct_queue.py |
Improve my code by adding docstrings |
from __future__ import annotations
import fractions
def invert_matrix(
matrix: list[list[int | float]],
) -> list[list[int | float | fractions.Fraction]]:
if not _array_is_matrix(matrix):
return [[-1]]
elif len(matrix) != len(matrix[0]):
return [[-2]]
elif len(matrix) < 2:
re... | --- +++ @@ -1,3 +1,17 @@+"""
+Matrix Inversion
+
+Compute the inverse of an invertible n x n matrix A, returning an n x n
+matrix B such that A * B = B * A = I (the identity matrix). Uses cofactor
+expansion: compute the matrix of minors with checkerboard signs, adjugate
+(transpose), and multiply by 1/determinant.
+
+... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/matrix_inversion.py |
Add docstrings including usage examples |
from __future__ import annotations
def sparse_multiply(
mat_a: list[list[int]], mat_b: list[list[int]]
) -> list[list[int]] | None:
if mat_a is None or mat_b is None:
return None
rows_a, cols_a = len(mat_a), len(mat_a[0])
cols_b = len(mat_b[0])
if len(mat_b) != cols_a:
raise Excep... | --- +++ @@ -1,3 +1,16 @@+"""
+Sparse Matrix Multiplication
+
+Given two sparse matrices A and B, return their product A * B.
+Skips zero elements for efficiency. A's column count must equal
+B's row count.
+
+Reference: https://leetcode.com/problems/sparse-matrix-multiplication/
+
+Complexity:
+ Time: O(m * n * p) ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/sparse_mul.py |
Include argument descriptions in docstrings |
from __future__ import annotations
from collections import defaultdict
def valid_solution_hashtable(board: list[list[int]]) -> bool:
for i in range(len(board)):
row_seen = defaultdict(int)
col_seen = defaultdict(int)
for j in range(len(board[0])):
value_row = board[i][j]
... | --- +++ @@ -1,3 +1,16 @@+"""
+Sudoku Validator
+
+Validate whether a completed 9x9 Sudoku board is a valid solution.
+Each row, column, and 3x3 sub-box must contain digits 1-9 without
+repetition. Boards containing zeroes are considered invalid.
+
+Reference: https://en.wikipedia.org/wiki/Sudoku
+
+Complexity:
+ Tim... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/sudoku_validator.py |
Create simple docstrings for beginners |
from __future__ import annotations
def multiply(
multiplicand: list[list[int]], multiplier: list[list[int]]
) -> list[list[int]]:
multiplicand_rows, multiplicand_cols = len(multiplicand), len(multiplicand[0])
multiplier_rows, multiplier_cols = len(multiplier), len(multiplier[0])
if multiplicand_cols ... | --- +++ @@ -1,3 +1,15 @@+"""
+Matrix Multiplication
+
+Multiply two compatible matrices and return their product. The number of
+columns in the multiplicand must equal the number of rows in the multiplier.
+
+Reference: https://en.wikipedia.org/wiki/Matrix_multiplication
+
+Complexity:
+ Time: O(m * n * p) for (m ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/multiply.py |
Improve documentation using docstrings |
from __future__ import annotations
def search_in_a_sorted_matrix(
mat: list[list[int]], rows: int, cols: int, key: int
) -> bool:
i, j = rows - 1, 0
while i >= 0 and j < cols:
if key == mat[i][j]:
return True
if key < mat[i][j]:
i -= 1
else:
j +... | --- +++ @@ -1,3 +1,16 @@+"""
+Search in Sorted Matrix
+
+Search for a key in a matrix that is sorted row-wise and column-wise
+in non-decreasing order. Start from the bottom-left corner and move
+up or right depending on the comparison.
+
+Reference: https://leetcode.com/problems/search-a-2d-matrix-ii/
+
+Complexity:
+... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/search_in_sorted_matrix.py |
Add detailed documentation for each class |
from __future__ import annotations
from collections import deque
class MovingAverage:
def __init__(self, size: int) -> None:
self.queue: deque[int] = deque(maxlen=size)
def next(self, val: int) -> float:
self.queue.append(val)
return sum(self.queue) / len(self.queue) | --- +++ @@ -1,3 +1,15 @@+"""
+Moving Average from Data Stream
+
+Calculate the moving average of integers in a sliding window of fixed
+size using a bounded deque.
+
+Reference: https://leetcode.com/problems/moving-average-from-data-stream/
+
+Complexity:
+ Time: O(1) per call to next
+ Space: O(size)
+"""
fr... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/queue/moving_average.py |
Add return value explanations in docstrings |
from __future__ import annotations
from heapq import heappop, heappush
def sort_diagonally(mat: list[list[int]]) -> list[list[int]]:
if len(mat) == 1 or len(mat[0]) == 1:
return mat
num_rows = len(mat)
num_cols = len(mat[0])
for i in range(num_rows + num_cols - 1):
if i + 1 < num_r... | --- +++ @@ -1,3 +1,16 @@+"""
+Sort Matrix Diagonally
+
+Given an m x n matrix of integers, sort each diagonal from top-left to
+bottom-right in ascending order and return the sorted matrix. Uses a
+min-heap for each diagonal.
+
+Reference: https://leetcode.com/problems/sort-the-matrix-diagonally/
+
+Complexity:
+ Ti... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/sort_matrix_diagonally.py |
Write docstrings including parameters and return values |
from __future__ import annotations
import collections
def max_sliding_window(arr: list[int], k: int) -> list[int]:
index_deque: collections.deque[int] = collections.deque()
result: list[int] = []
for i, value in enumerate(arr):
while index_deque and arr[index_deque[-1]] < value:
inde... | --- +++ @@ -1,3 +1,16 @@+"""
+Max Sliding Window (Deque-based)
+
+Given an array and a window size k, find the maximum element in each
+sliding window using a monotonic deque that stores indices of elements
+in decreasing order of their values.
+
+Reference: https://leetcode.com/problems/sliding-window-maximum/
+
+Comp... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/queue/max_sliding_window.py |
Add docstrings to my Python code |
from __future__ import annotations
def pythagoras(
opposite: float | str, adjacent: float | str, hypotenuse: float | str
) -> str:
try:
if opposite == "?":
return "Opposite = " + str(((hypotenuse**2) - (adjacent**2)) ** 0.5)
if adjacent == "?":
return "Adjacent = " + s... | --- +++ @@ -1,3 +1,15 @@+"""
+Pythagorean Theorem
+
+Given the lengths of two sides of a right-angled triangle, compute the
+length of the third side using the Pythagorean theorem.
+
+Reference: https://en.wikipedia.org/wiki/Pythagorean_theorem
+
+Complexity:
+ Time: O(1)
+ Space: O(1)
+"""
from __future__ im... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/math/pythagoras.py |
Create documentation strings for testing functions |
from __future__ import annotations
import copy
import math
def maximum_flow_dfs(adjacency_matrix: list[list[int]]) -> int:
new_array = copy.deepcopy(adjacency_matrix)
total = 0
while True:
min_flow = math.inf
visited = [0] * len(new_array)
path = [0] * len(new_array)
st... | --- +++ @@ -1,3 +1,15 @@+"""
+Maximum Flow via DFS
+
+Computes maximum flow in a network represented as an adjacency matrix,
+using DFS to find augmenting paths.
+
+Reference: https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm
+
+Complexity:
+ Time: O(E * f) where f is the max flow value
+ Space: O(... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/maximum_flow_dfs.py |
Add well-formatted docstrings |
from __future__ import annotations
def sum_sub_squares(matrix: list[list[int]], k: int) -> list[list[int]] | None:
size = len(matrix)
if k > size:
return None
result_size = size - k + 1
result = [[0] * result_size for _ in range(result_size)]
for i in range(result_size):
for j in ... | --- +++ @@ -1,8 +1,33 @@+"""
+Sum of Sub-Squares
+
+Given a square matrix of size n x n and an integer k, compute the sum
+of all k x k sub-squares and return the results as a matrix.
+
+Reference: https://www.geeksforgeeks.org/given-n-x-n-square-matrix-find-sum-sub-squares-size-k-x-k/
+
+Complexity:
+ Time: O(n^2 ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/sum_sub_squares.py |
Add docstrings for utility scripts |
from __future__ import annotations
class Edge:
def __init__(self, source: int, target: int, weight: int) -> None:
self.source = source
self.target = target
self.weight = weight
class DisjointSet:
def __init__(self, size: int) -> None:
self.parent = list(range(size))
... | --- +++ @@ -1,8 +1,21 @@+"""
+Minimum Spanning Tree (Kruskal's Algorithm)
+
+Finds the MST of an undirected graph using Kruskal's algorithm with a
+disjoint-set (union-find) data structure.
+
+Reference: https://en.wikipedia.org/wiki/Kruskal%27s_algorithm
+
+Complexity:
+ Time: O(E log E)
+ Space: O(V)
+"""
f... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/minimum_spanning_tree.py |
Document my Python code with docstrings |
from __future__ import annotations
def spiral_traversal(matrix: list[list[int]]) -> list[int]:
result: list[int] = []
if len(matrix) == 0:
return result
row_begin = 0
row_end = len(matrix) - 1
col_begin = 0
col_end = len(matrix[0]) - 1
while row_begin <= row_end and col_begin <= ... | --- +++ @@ -1,8 +1,32 @@+"""
+Spiral Traversal
+
+Return all elements of an m x n matrix in spiral order, traversing
+right, down, left, and up repeatedly while shrinking the boundaries.
+
+Reference: https://leetcode.com/problems/spiral-matrix/
+
+Complexity:
+ Time: O(m * n)
+ Space: O(m * n)
+"""
from __fu... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/spiral_traversal.py |
Add well-formatted docstrings |
from __future__ import annotations
def count_paths(rows: int, cols: int) -> int:
if rows < 1 or cols < 1:
return -1
count = [[None for _ in range(cols)] for _ in range(rows)]
for i in range(cols):
count[0][i] = 1
for j in range(rows):
count[j][0] = 1
for i in range(1, ro... | --- +++ @@ -1,8 +1,34 @@+"""
+Count Paths
+
+Count the number of unique paths from the top-left corner to the
+bottom-right corner of an m x n grid. Movement is restricted to
+right or down only. Uses dynamic programming.
+
+Reference: https://leetcode.com/problems/unique-paths/
+
+Complexity:
+ Time: O(m * n)
+ ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/matrix/count_paths.py |
Create docstrings for each class method |
from __future__ import annotations
class Graph:
def __init__(self, vertices: int) -> None:
self.vertex_count = vertices
self.graph: dict[int, list[int]] = {}
self.closure = [[0 for _ in range(vertices)] for _ in range(vertices)]
def add_edge(self, source: int, target: int) -> None:
... | --- +++ @@ -1,21 +1,51 @@+"""
+Transitive Closure via DFS
+
+Computes the transitive closure of a directed graph using depth-first
+search.
+
+Reference: https://en.wikipedia.org/wiki/Transitive_closure#In_graph_theory
+
+Complexity:
+ Time: O(V * (V + E))
+ Space: O(V^2)
+"""
from __future__ import annotatio... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/transitive_closure_dfs.py |
Create docstrings for all classes and functions |
from __future__ import annotations
def binary_search(array: list[int], query: int) -> int:
low, high = 0, len(array) - 1
while low <= high:
mid = low + (high - low) // 2
val = array[mid]
if val == query:
return mid
if val < query:
low = mid + 1
... | --- +++ @@ -1,8 +1,35 @@+"""
+Binary Search
+
+Search for an element in a sorted array by repeatedly dividing the search
+interval in half.
+
+Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm
+
+Complexity:
+ Time: O(1) best / O(log n) average / O(log n) worst
+ Space: O(1) iterative, O(log n) re... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/binary_search.py |
Write docstrings for data processing functions |
from __future__ import annotations
def bead_sort(array: list[int]) -> list[int]:
if any(num < 0 for num in array):
raise ValueError("Bead sort only works with non-negative integers.")
max_value = max(array) if array else 0
grid = [[0] * len(array) for _ in range(max_value)]
# Drop beads (pl... | --- +++ @@ -1,8 +1,35 @@+"""
+Bead Sort
+
+Bead sort (also known as gravity sort) simulates how beads settle under
+gravity on an abacus. It only works with non-negative integers.
+
+Reference: https://en.wikipedia.org/wiki/Bead_sort
+
+Complexity:
+ Time: O(n) best / O(n * max_value) average / O(n * max_value) wo... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/bead_sort.py |
Improve documentation using docstrings |
from __future__ import annotations
_GRAY, _BLACK = 0, 1
def top_sort_recursive(graph: dict[str, list[str]]) -> list[str]:
order: list[str] = []
enter = set(graph)
state: dict[str, int] = {}
def _dfs(node: str) -> None:
state[node] = _GRAY
for neighbour in graph.get(node, ()):
... | --- +++ @@ -1,3 +1,17 @@+"""
+Topological Sort
+
+Topological sort produces a linear ordering of vertices in a directed
+acyclic graph (DAG) such that for every directed edge (u, v), vertex u
+comes before v. Two implementations are provided: one recursive
+(DFS-based) and one iterative.
+
+Reference: https://en.wikip... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/topological_sort_dfs.py |
Write docstrings that follow conventions |
from __future__ import annotations
def find_min_rotate(array: list[int]) -> int:
low = 0
high = len(array) - 1
while low < high:
mid = (low + high) // 2
if array[mid] > array[high]:
low = mid + 1
else:
high = mid
return array[low]
def find_min_rotate_... | --- +++ @@ -1,8 +1,34 @@+"""
+Find Minimum in Rotated Sorted Array
+
+Find the minimum element in a sorted array that has been rotated at some
+unknown pivot. Assumes no duplicates exist in the array.
+
+Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm
+
+Complexity:
+ Time: O(1) best / O(log n) ave... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/find_min_rotate.py |
Create docstrings for API functions |
from __future__ import annotations
def linear_search(array: list[int], query: int) -> int:
for i, value in enumerate(array):
if value == query:
return i
return -1 | --- +++ @@ -1,9 +1,36 @@+"""
+Linear Search
+
+Search for a target value in an array by checking every element sequentially.
+The array does not need to be sorted.
+
+Reference: https://en.wikipedia.org/wiki/Linear_search
+
+Complexity:
+ Time: O(1) best / O(n) average / O(n) worst
+ Space: O(1)
+"""
from __f... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/linear_search.py |
Document this script properly |
from __future__ import annotations
def search_insert(array: list[int], val: int) -> int:
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if val > array[mid]:
low = mid + 1
else:
high = mid - 1
return low | --- +++ @@ -1,8 +1,41 @@+"""
+Search Insert Position
+
+Given a sorted array and a target value, return the index if the target is
+found. If not, return the index where it would be if it were inserted in
+order.
+
+Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm
+
+Complexity:
+ Time: O(1) best /... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/search_insert.py |
Improve my code by adding docstrings |
from __future__ import annotations
def find_path(maze: list[list[int]]) -> int:
cnt = _dfs(maze, 0, 0, 0, -1)
return cnt
def _dfs(
maze: list[list[int]],
i: int,
j: int,
depth: int,
cnt: int,
) -> int:
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
row = len(maze)
col = le... | --- +++ @@ -1,8 +1,31 @@+"""
+Maze Search (DFS)
+
+Find the shortest path from the top-left corner to the bottom-right corner
+of a grid using depth-first search with backtracking. Only cells with
+value 1 may be traversed. Returns -1 if no path exists.
+
+Complexity:
+ Time: O(4^(M*N)) worst case (backtracking)
... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/maze_search_dfs.py |
Document classes and their methods |
from __future__ import annotations
def first_occurrence(array: list[int], query: int) -> int:
low, high = 0, len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if low == high:
break
if array[mid] < query:
low = mid + 1
else:
hig... | --- +++ @@ -1,8 +1,35 @@+"""
+First Occurrence
+
+Find the index of the first occurrence of a target value in a sorted array
+using binary search.
+
+Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm
+
+Complexity:
+ Time: O(1) best / O(log n) average / O(log n) worst
+ Space: O(1)
+"""
from __... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/first_occurrence.py |
Add docstrings to make code maintainable |
from __future__ import annotations
_KEYBOARD_ROWS: list[set[str]] = [
set("qwertyuiop"),
set("asdfghjkl"),
set("zxcvbnm"),
]
def find_keyboard_row(words: list[str]) -> list[str]:
result: list[str] = []
for word in words:
for row in _KEYBOARD_ROWS:
if set(word.lower()).issubse... | --- +++ @@ -1,3 +1,15 @@+"""
+Keyboard Row Filter
+
+Given a list of words, return the words that can be typed using letters from
+only one row of an American QWERTY keyboard.
+
+Reference: https://leetcode.com/problems/keyboard-row/description/
+
+Complexity:
+ Time: O(n * m) where n is the number of words and m i... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/set/find_keyboard_row.py |
Help me comply with documentation standards |
from __future__ import annotations
from itertools import chain, combinations
def _powerset(iterable: list[str]) -> chain[tuple[str, ...]]:
items = list(iterable)
return chain.from_iterable(combinations(items, r) for r in range(len(items) + 1))
def optimal_set_cover(
universe: set[int],
subsets: di... | --- +++ @@ -1,3 +1,19 @@+"""
+Set Cover Problem
+
+Given a universe U of n elements, a collection S of subsets of U, and a cost
+for each subset, find the minimum-cost sub-collection that covers all of U.
+
+Reference: https://en.wikipedia.org/wiki/Set_cover_problem
+
+Complexity:
+ optimal_set_cover:
+ Time:... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/set/set_covering.py |
Write documentation strings for class attributes |
from __future__ import annotations
import random
class RandomizedSet:
def __init__(self) -> None:
self.elements: list[int] = []
self.index_map: dict[int, int] = {}
def insert(self, new_one: int) -> None:
if new_one in self.index_map:
return
self.index_map[new_on... | --- +++ @@ -1,3 +1,15 @@+"""
+Randomized Set
+
+A data structure that supports insert, remove, and get-random-element
+operations, all in average O(1) time.
+
+Reference: https://leetcode.com/problems/insert-delete-getrandom-o1/
+
+Complexity:
+ Time: O(1) average for insert, remove, and random_element
+ Space: ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/set/randomized_set.py |
Add verbose docstrings with examples |
from __future__ import annotations
def last_occurrence(array: list[int], query: int) -> int:
low, high = 0, len(array) - 1
while low <= high:
mid = (high + low) // 2
if (array[mid] == query and mid == len(array) - 1) or (
array[mid] == query and array[mid + 1] > query
):
... | --- +++ @@ -1,8 +1,35 @@+"""
+Last Occurrence
+
+Find the index of the last occurrence of a target value in a sorted array
+using binary search.
+
+Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm
+
+Complexity:
+ Time: O(1) best / O(log n) average / O(log n) worst
+ Space: O(1)
+"""
from __fu... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/last_occurrence.py |
Add docstrings that explain purpose and usage |
from __future__ import annotations
def ternary_search(left: int, right: int, key: int, array: list[int]) -> int:
while right >= left:
mid1 = left + (right - left) // 3
mid2 = right - (right - left) // 3
if key == array[mid1]:
return mid1
if key == array[mid2]:
... | --- +++ @@ -1,8 +1,38 @@+"""
+Ternary Search
+
+Search for a target value in a sorted array by dividing the search range into
+three equal parts instead of two. At each step two midpoints are computed and
+the search range is narrowed to one third.
+
+Reference: https://en.wikipedia.org/wiki/Ternary_search
+
+Complexi... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/ternary_search.py |
Add docstrings for internal functions |
from __future__ import annotations
def search_rotate(array: list[int], val: int) -> int:
low, high = 0, len(array) - 1
while low <= high:
mid = (low + high) // 2
if val == array[mid]:
return mid
if array[low] <= array[mid]:
if array[low] <= val <= array[mid]:
... | --- +++ @@ -1,8 +1,37 @@+"""
+Search in Rotated Sorted Array
+
+Search for a target value in an array that was sorted in ascending order and
+then rotated at some unknown pivot. One half of the array is always in sorted
+order; we identify that half and decide which side to search.
+
+Reference: https://en.wikipedia.o... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/search_rotate.py |
Add docstrings for better understanding |
from __future__ import annotations
from collections.abc import Callable
def binary_search_first_true(
low: int,
high: int,
predicate: Callable[[int], bool],
) -> int:
result = -1
while low <= high:
mid = low + (high - low) // 2
if predicate(mid):
result = mid
... | --- +++ @@ -1,3 +1,17 @@+"""
+Generalized Binary Search
+
+Find the smallest value in a numeric range for which a monotonic boolean
+predicate evaluates to True. Instead of searching for a specific value in
+an array, this version accepts an arbitrary predicate, allowing the same
+binary search logic to be reused acro... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/generalized_binary_search.py |
Write docstrings for algorithm functions |
from __future__ import annotations
from collections import deque
class ZigZagIterator:
def __init__(self, v1: list[int], v2: list[int]) -> None:
self.queue: deque[list[int]] = deque(lst for lst in (v1, v2) if lst)
def next(self) -> int:
current_list = self.queue.popleft()
ret = cur... | --- +++ @@ -1,3 +1,15 @@+"""
+Zigzag Iterator
+
+Interleave elements from two lists in a zigzag fashion. Elements are
+yielded alternately from each list until both are exhausted.
+
+Reference: https://leetcode.com/problems/zigzag-iterator/
+
+Complexity:
+ Time: O(n) total across all next() calls
+ Space: O(n)
... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/queue/zigzagiterator.py |
Add docstrings to improve collaboration |
from __future__ import annotations
def bitonic_sort(array: list[int], reverse: bool = False) -> list[int]:
n = len(array)
if n <= 1:
return array
if not (n and not (n & (n - 1))):
raise ValueError("the size of input should be power of two")
left = bitonic_sort(array[: n // 2], True)
... | --- +++ @@ -1,8 +1,37 @@+"""
+Bitonic Sort
+
+Bitonic sort is a comparison-based sorting algorithm designed for parallel
+execution. This implementation is sequential. The input size must be a
+power of two.
+
+Reference: https://en.wikipedia.org/wiki/Bitonic_sorter
+
+Complexity:
+ Time: O(n log^2 n) best / O(n ... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/bitonic_sort.py |
Write docstrings for utility functions |
from __future__ import annotations
from collections import defaultdict, deque
def topological_sort(vertices: int, edges: list[tuple[int, int]]) -> list[int]:
graph: dict[int, list[int]] = defaultdict(list)
in_degree = [0] * vertices
for u, v in edges:
graph[u].append(v)
in_degree[v] +=... | --- +++ @@ -1,37 +1,65 @@-
-from __future__ import annotations
-
-from collections import defaultdict, deque
-
-
-def topological_sort(vertices: int, edges: list[tuple[int, int]]) -> list[int]:
- graph: dict[int, list[int]] = defaultdict(list)
-
- in_degree = [0] * vertices
-
- for u, v in edges:
- grap... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/graph/topological_sort_bfs.py |
Document classes and their methods |
from __future__ import annotations
def sentinel_search(arr: list[int], target: int) -> int:
n = len(arr)
if n == 0:
return -1
last = arr[-1]
arr[-1] = target
i = 0
while arr[i] != target:
i += 1
arr[-1] = last
if i < n - 1 or arr[-1] == target:
return i
ret... | --- +++ @@ -1,8 +1,21 @@+"""Sentinel linear search — a small optimisation over naive linear search.
+
+By placing the target at the end of the array (as a sentinel), we can
+remove the bounds check from the inner loop, roughly halving comparisons.
+
+Time: O(n) — same asymptotic complexity but fewer comparisons in prac... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/sentinel_search.py |
Add clean documentation to messy code |
from __future__ import annotations
def bubble_sort(array: list[int]) -> list[int]:
n = len(array)
swapped = True
passes = 0
while swapped:
swapped = False
for i in range(1, n - passes):
if array[i - 1] > array[i]:
array[i - 1], array[i] = array[i], array[i ... | --- +++ @@ -1,8 +1,32 @@+"""
+Bubble Sort
+
+Bubble sort repeatedly steps through the list, compares adjacent elements
+and swaps them if they are in the wrong order.
+
+Reference: https://en.wikipedia.org/wiki/Bubble_sort
+
+Complexity:
+ Time: O(n) best / O(n^2) average / O(n^2) worst
+ Space: O(1)
+"""
fro... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/bubble_sort.py |
Help me add docstrings to my project |
from __future__ import annotations
import random
def bogo_sort(array: list[int]) -> list[int]:
while not _is_sorted(array):
random.shuffle(array)
return array
def _is_sorted(array: list[int]) -> bool:
return all(
array[i] <= array[i + 1] for i in range(len(array) - 1)
) | --- +++ @@ -1,3 +1,15 @@+"""
+Bogo Sort
+
+Bogo sort repeatedly shuffles the array at random until it happens to be
+sorted. It is extremely inefficient and used only for educational purposes.
+
+Reference: https://en.wikipedia.org/wiki/Bogosort
+
+Complexity:
+ Time: O(n) best / O(n * n!) average / O(infinity) wo... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/bogo_sort.py |
Write docstrings describing each step |
from __future__ import annotations
def cocktail_shaker_sort(array: list[int]) -> list[int]:
n = len(array)
swapped = True
while swapped:
swapped = False
for i in range(1, n):
if array[i - 1] > array[i]:
array[i - 1], array[i] = array[i], array[i - 1]
... | --- +++ @@ -1,8 +1,32 @@+"""
+Cocktail Shaker Sort
+
+Cocktail shaker sort is a variation of bubble sort that traverses the
+list alternately from left-to-right and right-to-left.
+
+Reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort
+
+Complexity:
+ Time: O(n) best / O(n^2) average / O(n^2) worst
+ S... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/sorting/cocktail_shaker_sort.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.