sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
keon/algorithms:algorithms/bit_manipulation/swap_pair.py
""" 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 def swap_pair(number: int) -> int: """Swap every pair of adjacent bits in an integer. Masks odd-positioned bits (0xAAAAAAAA), shifts them right by one, masks even-positioned bits (0x55555555), shifts them left by one, and merges the results. Args: number: A non-negative integer. Returns: The integer with each adjacent pair of bits swapped. Examples: >>> swap_pair(22) 41 >>> swap_pair(10) 5 """ odd_bits = (number & int("AAAAAAAA", 16)) >> 1 even_bits = (number & int("55555555", 16)) << 1 return odd_bits | even_bits
{ "repo_id": "keon/algorithms", "file_path": "algorithms/bit_manipulation/swap_pair.py", "license": "MIT License", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/common/graph.py
"""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 on the same object. """ from __future__ import annotations from dataclasses import dataclass, field @dataclass class Graph: """A weighted directed graph using adjacency dict representation. Supports weighted/unweighted and directed/undirected graphs. The graph is stored as ``{node: {neighbor: weight}}``. For unweighted graphs, use the :meth:`unweighted` factory or set weights to 1. Attributes: adj: Adjacency dict mapping each node to ``{neighbor: weight}``. directed: Whether this is a directed graph. Examples: >>> g = Graph({"a": {"b": 1, "c": 4}, "b": {"c": 2}}) >>> g.adj["a"] {'b': 1, 'c': 4} >>> g = Graph.unweighted({"a": ["b", "c"], "b": ["c"]}) >>> g.adj["a"] {'b': 1, 'c': 1} """ 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: """Create a graph from an unweighted adjacency list. Args: adj: Mapping of node to list of neighbors. directed: Whether edges are one-directional. Returns: A Graph with all edge weights set to 1. Examples: >>> g = Graph.unweighted({"a": ["b", "c"], "b": ["c"]}) >>> g.adj["b"] {'c': 1} """ weighted = { node: {neighbor: 1 for neighbor in neighbors} for node, neighbors in adj.items() } return cls(adj=weighted, directed=directed) def nodes(self) -> set[str]: """Return all nodes in the graph. Returns: Set of all node identifiers, including nodes that only appear as neighbors. Examples: >>> g = Graph({"a": {"b": 1}}) >>> sorted(g.nodes()) ['a', 'b'] """ all_nodes: set[str] = set(self.adj.keys()) for neighbors in self.adj.values(): all_nodes.update(neighbors.keys()) return all_nodes def add_edge(self, source: str, target: str, weight: float = 1) -> None: """Add an edge to the graph. For undirected graphs, the reverse edge is also added. Args: source: Source node. target: Target node. weight: Edge weight (default 1). Examples: >>> g = Graph() >>> g.add_edge("a", "b", 5) >>> g.adj["a"]["b"] 5 """ if source not in self.adj: self.adj[source] = {} self.adj[source][target] = weight if not self.directed: if target not in self.adj: self.adj[target] = {} self.adj[target][source] = weight
{ "repo_id": "keon/algorithms", "file_path": "algorithms/common/graph.py", "license": "MIT License", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/common/list_node.py
"""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 palindrome. """ from __future__ import annotations from dataclasses import dataclass @dataclass class ListNode: """A node in a singly linked list. Attributes: val: The value stored in this node. next: Reference to the next node. Examples: >>> head = ListNode(1, ListNode(2, ListNode(3))) >>> head.val 1 >>> head.next.val 2 """ val: int = 0 next: ListNode | None = None
{ "repo_id": "keon/algorithms", "file_path": "algorithms/common/list_node.py", "license": "MIT License", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/common/tree_node.py
"""Binary tree node shared across all tree algorithms. This module provides the universal TreeNode used by every tree algorithm in this library. Using a single shared type means you can compose algorithms freely: build a BST, invert it, then traverse it. """ from __future__ import annotations from dataclasses import dataclass @dataclass class TreeNode: """A node in a binary tree. Attributes: val: The value stored in this node. left: Reference to the left child. right: Reference to the right child. Examples: >>> root = TreeNode(1, TreeNode(2), TreeNode(3)) >>> root.left.val 2 >>> root.right.val 3 """ val: int = 0 left: TreeNode | None = None right: TreeNode | None = None
{ "repo_id": "keon/algorithms", "file_path": "algorithms/common/tree_node.py", "license": "MIT License", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/data_structures/b_tree.py
""" 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: Time: O(log n) for search, insert, and delete Space: O(n) """ from __future__ import annotations class Node: """A node in a B-tree containing keys and child pointers. Examples: >>> node = Node() >>> node.keys [] """ def __init__(self) -> None: self.keys: list = [] self.children: list[Node] = [] def __repr__(self) -> str: """Return a string representation of the node. Returns: A string showing the node's keys. """ return f"<id_node: {self.keys}>" @property def is_leaf(self) -> bool: """Check whether this node is a leaf. Returns: True if the node has no children, False otherwise. """ return len(self.children) == 0 class BTree: """A B-tree data structure supporting search, insertion, and deletion. Args: t_val: The minimum degree of the B-tree. Examples: >>> bt = BTree(2) >>> bt.insert_key(10) >>> bt.find(10) True """ def __init__(self, t_val: int = 2) -> None: self.min_numbers_of_keys = t_val - 1 self.max_number_of_keys = 2 * t_val - 1 self.root = Node() def _split_child(self, parent: Node, child_index: int) -> None: """Split a full child node into two nodes. Args: parent: The parent node whose child is being split. child_index: The index of the child to split. """ new_right_child = Node() half_max = self.max_number_of_keys // 2 child = parent.children[child_index] middle_key = child.keys[half_max] new_right_child.keys = child.keys[half_max + 1 :] child.keys = child.keys[:half_max] if not child.is_leaf: new_right_child.children = child.children[half_max + 1 :] child.children = child.children[: half_max + 1] parent.keys.insert(child_index, middle_key) parent.children.insert(child_index + 1, new_right_child) def insert_key(self, key: int) -> None: """Insert a key into the B-tree. Args: key: The key to insert. """ if len(self.root.keys) >= self.max_number_of_keys: new_root = Node() new_root.children.append(self.root) self.root = new_root self._split_child(new_root, 0) self._insert_to_nonfull_node(self.root, key) else: self._insert_to_nonfull_node(self.root, key) def _insert_to_nonfull_node(self, node: Node, key: int) -> None: """Insert a key into a non-full node. Args: node: The non-full node to insert into. key: The key to insert. """ i = len(node.keys) - 1 while i >= 0 and node.keys[i] >= key: i -= 1 if node.is_leaf: node.keys.insert(i + 1, key) else: if len(node.children[i + 1].keys) >= self.max_number_of_keys: self._split_child(node, i + 1) if node.keys[i + 1] < key: i += 1 self._insert_to_nonfull_node(node.children[i + 1], key) def find(self, key: int) -> bool: """Search for a key in the B-tree. Args: key: The key to search for. Returns: True if the key is found, False otherwise. Examples: >>> bt = BTree(2) >>> bt.insert_key(5) >>> bt.find(5) True >>> bt.find(3) False """ current_node = self.root while True: i = len(current_node.keys) - 1 while i >= 0 and current_node.keys[i] > key: i -= 1 if i >= 0 and current_node.keys[i] == key: return True if current_node.is_leaf: return False current_node = current_node.children[i + 1] def remove_key(self, key: int) -> None: """Remove a key from the B-tree. Args: key: The key to remove. """ self._remove_key(self.root, key) def _remove_key(self, node: Node, key: int) -> bool: """Recursively remove a key from the subtree rooted at node. Args: node: The root of the subtree to remove from. key: The key to remove. Returns: True if the key was found and removed, False otherwise. """ try: key_index = node.keys.index(key) if node.is_leaf: node.keys.remove(key) else: self._remove_from_nonleaf_node(node, key_index) return True except ValueError: if node.is_leaf: return False else: i = 0 number_of_keys = len(node.keys) while i < number_of_keys and key > node.keys[i]: i += 1 action_performed = self._repair_tree(node, i) if action_performed: return self._remove_key(node, key) else: return self._remove_key(node.children[i], key) def _repair_tree(self, node: Node, child_index: int) -> bool: """Repair the tree after a deletion to maintain B-tree properties. Args: node: The parent node of the child that may need repair. child_index: The index of the child to check. Returns: True if a structural repair was performed, False otherwise. """ child = node.children[child_index] if self.min_numbers_of_keys < len(child.keys) <= self.max_number_of_keys: return False if ( child_index > 0 and len(node.children[child_index - 1].keys) > self.min_numbers_of_keys ): self._rotate_right(node, child_index) return True if ( child_index < len(node.children) - 1 and len(node.children[child_index + 1].keys) > self.min_numbers_of_keys ): self._rotate_left(node, child_index) return True if child_index > 0: self._merge(node, child_index - 1, child_index) else: self._merge(node, child_index, child_index + 1) return True def _rotate_left(self, parent_node: Node, child_index: int) -> None: """Take a key from the right sibling and transfer it to the child. Args: parent_node: The parent node. child_index: The index of the child receiving the key. """ new_child_key = parent_node.keys[child_index] new_parent_key = parent_node.children[child_index + 1].keys.pop(0) parent_node.children[child_index].keys.append(new_child_key) parent_node.keys[child_index] = new_parent_key if not parent_node.children[child_index + 1].is_leaf: ownerless_child = parent_node.children[child_index + 1].children.pop(0) parent_node.children[child_index].children.append(ownerless_child) def _rotate_right(self, parent_node: Node, child_index: int) -> None: """Take a key from the left sibling and transfer it to the child. Args: parent_node: The parent node. child_index: The index of the child receiving the key. """ parent_key = parent_node.keys[child_index - 1] new_parent_key = parent_node.children[child_index - 1].keys.pop() parent_node.children[child_index].keys.insert(0, parent_key) parent_node.keys[child_index - 1] = new_parent_key if not parent_node.children[child_index - 1].is_leaf: ownerless_child = parent_node.children[child_index - 1].children.pop() parent_node.children[child_index].children.insert(0, ownerless_child) def _merge( self, parent_node: Node, to_merge_index: int, transferred_child_index: int ) -> None: """Merge two child nodes and a parent key into a single node. Args: parent_node: The parent node. to_merge_index: Index of the child that receives the merged data. transferred_child_index: Index of the child being merged in. """ from_merge_node = parent_node.children.pop(transferred_child_index) parent_key_to_merge = parent_node.keys.pop(to_merge_index) to_merge_node = parent_node.children[to_merge_index] to_merge_node.keys.append(parent_key_to_merge) to_merge_node.keys.extend(from_merge_node.keys) if not to_merge_node.is_leaf: to_merge_node.children.extend(from_merge_node.children) if parent_node == self.root and not parent_node.keys: self.root = to_merge_node def _remove_from_nonleaf_node( self, node: Node, key_index: int ) -> None: """Remove a key from a non-leaf node by replacing with predecessor/successor. Args: node: The non-leaf node containing the key. key_index: The index of the key to remove. """ key = node.keys[key_index] left_subtree = node.children[key_index] if len(left_subtree.keys) > self.min_numbers_of_keys: largest_key = self._find_largest_and_delete_in_left_subtree(left_subtree) elif len(node.children[key_index + 1].keys) > self.min_numbers_of_keys: largest_key = self._find_largest_and_delete_in_right_subtree( node.children[key_index + 1] ) else: self._merge(node, key_index, key_index + 1) return self._remove_key(node, key) node.keys[key_index] = largest_key def _find_largest_and_delete_in_left_subtree(self, node: Node) -> int: """Find and remove the largest key in the left subtree. Args: node: The root of the subtree. Returns: The largest key that was removed. """ if node.is_leaf: return node.keys.pop() else: ch_index = len(node.children) - 1 self._repair_tree(node, ch_index) largest_key_in_subtree = self._find_largest_and_delete_in_left_subtree( node.children[len(node.children) - 1] ) return largest_key_in_subtree def _find_largest_and_delete_in_right_subtree(self, node: Node) -> int: """Find and remove the smallest key in the right subtree. Args: node: The root of the subtree. Returns: The smallest key that was removed. """ if node.is_leaf: return node.keys.pop(0) else: ch_index = 0 self._repair_tree(node, ch_index) largest_key_in_subtree = self._find_largest_and_delete_in_right_subtree( node.children[0] ) return largest_key_in_subtree def traverse_tree(self) -> list: """Traverse the B-tree in order and return all keys. Returns: A list of all keys in sorted order. Examples: >>> bt = BTree(2) >>> for k in [3, 1, 2]: bt.insert_key(k) >>> bt.traverse_tree() [1, 2, 3] """ result: list = [] self._traverse_tree(self.root, result) return result def _traverse_tree(self, node: Node, result: list) -> None: """Recursively traverse the subtree and collect keys. Args: node: The root of the subtree to traverse. result: The list to append keys to. """ if node.is_leaf: result.extend(node.keys) else: for i, key in enumerate(node.keys): self._traverse_tree(node.children[i], result) result.append(key) self._traverse_tree(node.children[-1], result)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/b_tree.py", "license": "MIT License", "lines": 303, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/data_structures/fenwick_tree.py
""" 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 and calculate the sum of the elements. To update a value, simply do arr[i] = x. The first operation takes O(n) time and the second operation takes O(1) time. Another simple solution is to create an extra array and store the sum of the first i-th elements at the i-th index in this new array. The sum of a given range can now be calculated in O(1) time, but the update operation takes O(n) time now. This works well if there are a large number of query operations but a very few number of update operations. There are two solutions that can perform both the query and update operations in O(logn) time. 1. Fenwick Tree 2. Segment Tree Compared with Segment Tree, Binary Indexed Tree requires less space and is easier to implement. """ class Fenwick_Tree: # noqa: N801 def __init__(self, freq): self.arr = freq self.n = len(freq) def get_sum(self, bit_tree, i): """ Returns sum of arr[0..index]. This function assumes that the array is preprocessed and partial sums of array elements are stored in bit_tree[]. """ 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: # Add current element of bit_tree to sum s += bit_tree[i] # Move index to parent node in getSum View i -= i & (-i) return s def update_bit(self, bit_tree, i, v): """ Updates a node in Binary Index Tree (bit_tree) at given index in bit_tree. The given value 'val' is added to bit_tree[i] and all of its ancestors in tree. """ # index in bit_ree[] is 1 more than the index in arr[] i += 1 # Traverse all ancestors and add 'val' while i <= self.n: # Add 'val' to current node of bit_tree bit_tree[i] += v # Update index to that of parent in update View i += i & (-i) def construct(self): """ Constructs and returns a Binary Indexed Tree for given array of size n. """ # Create and initialize bit_ree[] as 0 bit_tree = [0] * (self.n + 1) # Store the actual values in bit_ree[] using update() for i in range(self.n): self.update_bit(bit_tree, i, self.arr[i]) return bit_tree
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/fenwick_tree.py", "license": "MIT License", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/data_structures/graph.py
""" 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) -> None: self.name = name @staticmethod def get_name(obj: object) -> str: """Return the name of *obj* whether it is a Node or a string. Args: obj: A Node instance or a string. Returns: The string name. """ if isinstance(obj, Node): return obj.name if isinstance(obj, str): return obj return "" def __eq__(self, obj: object) -> bool: return self.name == self.get_name(obj) def __repr__(self) -> str: return self.name def __hash__(self) -> int: return hash(self.name) def __ne__(self, obj: object) -> bool: return self.name != self.get_name(obj) def __lt__(self, obj: object) -> bool: return self.name < self.get_name(obj) def __le__(self, obj: object) -> bool: return self.name <= self.get_name(obj) def __gt__(self, obj: object) -> bool: return self.name > self.get_name(obj) def __ge__(self, obj: object) -> bool: return self.name >= self.get_name(obj) def __bool__(self) -> bool: return bool(self.name) class DirectedEdge: """A directed edge connecting two nodes.""" def __init__(self, node_from: Node, node_to: Node) -> None: self.source = node_from self.target = node_to def __eq__(self, obj: object) -> bool: if isinstance(obj, DirectedEdge): return obj.source == self.source and obj.target == self.target return False def __repr__(self) -> str: return f"({self.source} -> {self.target})" class DirectedGraph: """A directed graph storing nodes, edges and an adjacency list.""" def __init__(self, load_dict: dict[str, list[str]] | None = None) -> None: """Build a directed graph, optionally from a dictionary. Args: load_dict: Optional adjacency dict ``{vertex: [neighbours]}``. """ if load_dict is None: load_dict = {} self.nodes: list[Node] = [] self.edges: list[DirectedEdge] = [] self.adjacency_list: dict[Node, list[Node]] = {} if load_dict and isinstance(load_dict, dict): for vertex in load_dict: node_from = self.add_node(vertex) self.adjacency_list[node_from] = [] for neighbor in load_dict[vertex]: node_to = self.add_node(neighbor) self.adjacency_list[node_from].append(node_to) self.add_edge(vertex, neighbor) def add_node(self, node_name: str) -> Node: """Add a named node (or return it if it already exists). Args: node_name: Name of the node. Returns: The Node instance. """ try: return self.nodes[self.nodes.index(node_name)] except ValueError: node = Node(node_name) self.nodes.append(node) return node def add_edge(self, node_name_from: str, node_name_to: str) -> None: """Add a directed edge between two named nodes. Args: node_name_from: Source node name. node_name_to: Target node name. """ try: node_from = self.nodes[self.nodes.index(node_name_from)] node_to = self.nodes[self.nodes.index(node_name_to)] self.edges.append(DirectedEdge(node_from, node_to)) except ValueError: pass
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/graph.py", "license": "MIT License", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
keon/algorithms:algorithms/data_structures/hash_table.py
""" 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 Complexity: Time: O(1) average for put/get/del, O(n) worst case Space: O(n) """ from __future__ import annotations class HashTable: """Hash table using open addressing with linear probing. Examples: >>> ht = HashTable(10) >>> ht.put(1, 'one') >>> ht.get(1) 'one' """ _empty = object() _deleted = object() def __init__(self, size: int = 11) -> None: """Initialize the hash table. Args: size: Number of slots in the underlying array. """ self.size = size self._len = 0 self._keys: list[object] = [self._empty] * size self._values: list[object] = [self._empty] * size def put(self, key: int, value: object) -> None: """Insert or update a key-value pair. Args: key: The key to insert. value: The value associated with the key. Raises: ValueError: If the table is full. """ initial_hash = hash_ = self.hash(key) while True: if self._keys[hash_] is self._empty or self._keys[hash_] is self._deleted: self._keys[hash_] = key self._values[hash_] = value self._len += 1 return elif self._keys[hash_] == key: self._keys[hash_] = key self._values[hash_] = value return hash_ = self._rehash(hash_) if initial_hash == hash_: raise ValueError("Table is full") def get(self, key: int) -> object | None: """Retrieve the value for a given key. Args: key: The key to look up. Returns: The value associated with the key, or None if not found. """ initial_hash = hash_ = self.hash(key) while True: if self._keys[hash_] is self._empty: return None elif self._keys[hash_] == key: return self._values[hash_] hash_ = self._rehash(hash_) if initial_hash == hash_: return None def del_(self, key: int) -> None: """Delete a key-value pair. Args: key: The key to delete. """ initial_hash = hash_ = self.hash(key) while True: if self._keys[hash_] is self._empty: return None elif self._keys[hash_] == key: self._keys[hash_] = self._deleted self._values[hash_] = self._deleted self._len -= 1 return hash_ = self._rehash(hash_) if initial_hash == hash_: return None def hash(self, key: int) -> int: """Compute the hash index for a key. Args: key: The key to hash. Returns: Index into the internal array. """ return key % self.size def _rehash(self, old_hash: int) -> int: """Linear probing rehash. Args: old_hash: The previous hash index. Returns: Next index to probe. """ return (old_hash + 1) % self.size def __getitem__(self, key: int) -> object | None: return self.get(key) def __delitem__(self, key: int) -> None: return self.del_(key) def __setitem__(self, key: int, value: object) -> None: self.put(key, value) def __len__(self) -> int: return self._len class ResizableHashTable(HashTable): """Hash table that automatically doubles in size when load exceeds 2/3. Examples: >>> rht = ResizableHashTable() >>> rht.put(1, 'a') >>> rht.get(1) 'a' """ MIN_SIZE = 8 def __init__(self) -> None: super().__init__(self.MIN_SIZE) def put(self, key: int, value: object) -> None: """Insert or update, resizing if load factor exceeds two-thirds. Args: key: The key to insert. value: The value associated with the key. """ super().put(key, value) if len(self) >= (self.size * 2) / 3: self._resize() def _resize(self) -> None: """Double the table size and rehash all existing entries.""" keys, values = self._keys, self._values self.size *= 2 self._len = 0 self._keys = [self._empty] * self.size self._values = [self._empty] * self.size for key, value in zip(keys, values, strict=False): if key is not self._empty and key is not self._deleted: self.put(key, value)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/hash_table.py", "license": "MIT License", "lines": 139, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/data_structures/heap.py
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 insert and remove_min Space: O(n) """ from __future__ import annotations from abc import ABCMeta, abstractmethod class AbstractHeap(metaclass=ABCMeta): """Abstract base class for binary heap implementations.""" def __init__(self) -> None: # noqa: B027 """Initialize the abstract heap.""" @abstractmethod def perc_up(self, index: int) -> None: """Percolate element up to restore heap property. Args: index: Index of the element to percolate up. """ @abstractmethod def insert(self, val: int) -> None: """Insert a value into the heap. Args: val: The value to insert. """ @abstractmethod def perc_down(self, index: int) -> None: """Percolate element down to restore heap property. Args: index: Index of the element to percolate down. """ @abstractmethod def min_child(self, index: int) -> int: """Return the index of the smaller child. Args: index: Index of the parent node. Returns: Index of the smaller child. """ @abstractmethod def remove_min(self) -> int: """Remove and return the minimum element. Returns: The minimum value in the heap. """ class BinaryHeap(AbstractHeap): """Min binary heap using array representation. Examples: >>> heap = BinaryHeap() >>> heap.insert(5) >>> heap.insert(3) >>> heap.remove_min() 3 """ def __init__(self) -> None: """Initialize the binary heap with a sentinel at index 0.""" self.current_size: int = 0 self.heap: list[int] = [0] def perc_up(self, index: int) -> None: """Percolate element up to maintain the min-heap invariant. Args: index: Index of the element to percolate up. """ while index // 2 > 0: if self.heap[index] < self.heap[index // 2]: self.heap[index], self.heap[index // 2] = ( self.heap[index // 2], self.heap[index], ) index = index // 2 def insert(self, val: int) -> None: """Insert a value into the heap. Args: val: The value to insert. """ self.heap.append(val) self.current_size = self.current_size + 1 self.perc_up(self.current_size) def min_child(self, index: int) -> int: """Return the index of the smaller child of a parent node. Args: index: Index of the parent node. Returns: Index of the smaller child. """ if 2 * index + 1 > self.current_size: return 2 * index if self.heap[2 * index] > self.heap[2 * index + 1]: return 2 * index + 1 return 2 * index def perc_down(self, index: int) -> None: """Percolate element down to maintain the min-heap invariant. Args: index: Index of the element to percolate down. """ while 2 * index < self.current_size: smaller_child = self.min_child(index) if self.heap[smaller_child] < self.heap[index]: self.heap[smaller_child], self.heap[index] = ( self.heap[index], self.heap[smaller_child], ) index = smaller_child def remove_min(self) -> int: """Remove and return the minimum element from the heap. Returns: The minimum value. """ ret = self.heap[1] self.heap[1] = self.heap[self.current_size] self.current_size = self.current_size - 1 self.heap.pop() self.perc_down(1) return ret
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/heap.py", "license": "MIT License", "lines": 117, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/data_structures/linked_list.py
""" 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 """ from __future__ import annotations class SinglyLinkedListNode: """A node in a singly linked list. Attributes: value: The value stored in the node. next: Reference to the next node, or None. """ def __init__(self, value: object) -> None: self.value = value self.next: SinglyLinkedListNode | None = None class DoublyLinkedListNode: """A node in a doubly linked list. Attributes: value: The value stored in the node. next: Reference to the next node, or None. prev: Reference to the previous node, or None. """ def __init__(self, value: object) -> None: self.value = value self.next: DoublyLinkedListNode | None = None self.prev: DoublyLinkedListNode | None = None
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/linked_list.py", "license": "MIT License", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/data_structures/priority_queue.py
""" 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 Space: O(n) """ from __future__ import annotations import itertools from collections.abc import Iterable from typing import Any class PriorityQueueNode: """A node holding data and its priority. Args: data: The stored value. priority: The priority of this node. """ def __init__(self, data: Any, priority: Any) -> None: self.data = data self.priority = priority def __repr__(self) -> str: """Return a string representation of the node. Returns: Formatted string with data and priority. """ return f"{self.data}: {self.priority}" class PriorityQueue: """Priority queue backed by a sorted linear array. Examples: >>> pq = PriorityQueue([3, 1, 2]) >>> pq.pop() 1 >>> pq.size() 2 """ def __init__( self, items: Iterable[Any] | None = None, priorities: Iterable[Any] | None = None, ) -> None: """Create a priority queue, optionally from items and priorities. Args: items: Initial items to insert. priorities: Corresponding priorities; defaults to item values. """ self.priority_queue_list: list[PriorityQueueNode] = [] if items is None: return if priorities is None: priorities = itertools.repeat(None) for item, priority in zip(items, priorities, strict=False): self.push(item, priority=priority) def __repr__(self) -> str: """Return a string representation of the priority queue. Returns: Formatted string. """ return f"PriorityQueue({self.priority_queue_list!r})" def size(self) -> int: """Return the number of elements in the queue. Returns: The queue size. """ return len(self.priority_queue_list) def push(self, item: Any, priority: Any = None) -> None: """Insert an item with the given priority. Args: item: The value to insert. priority: Priority value; defaults to the item itself. """ priority = item if priority is None else priority node = PriorityQueueNode(item, priority) for index, current in enumerate(self.priority_queue_list): if current.priority < node.priority: self.priority_queue_list.insert(index, node) return self.priority_queue_list.append(node) def pop(self) -> Any: """Remove and return the item with the lowest priority. Returns: The data of the lowest-priority node. """ return self.priority_queue_list.pop().data
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/priority_queue.py", "license": "MIT License", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/data_structures/queue.py
""" 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/dequeue/peek (amortized for ArrayQueue) Space: O(n) """ from __future__ import annotations from abc import ABCMeta, abstractmethod from collections.abc import Iterator class AbstractQueue(metaclass=ABCMeta): """Abstract base class for queue implementations.""" def __init__(self) -> None: self._size = 0 def __len__(self) -> int: return self._size def is_empty(self) -> bool: """Check if the queue is empty. Returns: True if the queue has no elements. """ return self._size == 0 @abstractmethod def enqueue(self, value: object) -> None: pass @abstractmethod def dequeue(self) -> object: pass @abstractmethod def peek(self) -> object: pass @abstractmethod def __iter__(self) -> Iterator[object]: pass class ArrayQueue(AbstractQueue): """Queue implemented with a dynamic array. Examples: >>> q = ArrayQueue() >>> q.enqueue(1) >>> q.dequeue() 1 """ def __init__(self, capacity: int = 10) -> None: """Initialize with a fixed-capacity array. Args: capacity: Initial capacity of the underlying array. """ super().__init__() self._array: list[object | None] = [None] * capacity self._front = 0 self._rear = 0 def __iter__(self) -> Iterator[object]: probe = self._front while True: if probe == self._rear: return yield self._array[probe] probe += 1 def enqueue(self, value: object) -> None: """Add an item to the rear of the queue. Args: value: The value to enqueue. """ if self._rear == len(self._array): self._expand() self._array[self._rear] = value self._rear += 1 self._size += 1 def dequeue(self) -> object: """Remove and return the front item. Returns: The front element. Raises: IndexError: If the queue is empty. """ if self.is_empty(): raise IndexError("Queue is empty") value = self._array[self._front] self._array[self._front] = None self._front += 1 self._size -= 1 return value def peek(self) -> object: """Return the front element without removing it. Returns: The front element. Raises: IndexError: If the queue is empty. """ if self.is_empty(): raise IndexError("Queue is empty") return self._array[self._front] def _expand(self) -> None: """Double the size of the underlying array.""" self._array += [None] * len(self._array) class QueueNode: """A single node in a linked-list-based queue.""" def __init__(self, value: object) -> None: self.value = value self.next: QueueNode | None = None class LinkedListQueue(AbstractQueue): """Queue implemented with a singly linked list. Examples: >>> q = LinkedListQueue() >>> q.enqueue(1) >>> q.dequeue() 1 """ def __init__(self) -> None: super().__init__() self._front: QueueNode | None = None self._rear: QueueNode | None = None def __iter__(self) -> Iterator[object]: probe = self._front while True: if probe is None: return yield probe.value probe = probe.next def enqueue(self, value: object) -> None: """Add an item to the rear of the queue. Args: value: The value to enqueue. """ node = QueueNode(value) if self._front is None: self._front = node self._rear = node else: self._rear.next = node self._rear = node self._size += 1 def dequeue(self) -> object: """Remove and return the front item. Returns: The front element. Raises: IndexError: If the queue is empty. """ if self.is_empty(): raise IndexError("Queue is empty") value = self._front.value if self._front is self._rear: self._front = None self._rear = None else: self._front = self._front.next self._size -= 1 return value def peek(self) -> object: """Return the front element without removing it. Returns: The front element. Raises: IndexError: If the queue is empty. """ if self.is_empty(): raise IndexError("Queue is empty") return self._front.value
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/queue.py", "license": "MIT License", "lines": 161, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/data_structures/segment_tree.py
""" Segment_tree creates a segment tree with a given array and function, allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ class SegmentTree: def __init__(self, arr, function): self.segment = [0 for x in range(3 * len(arr) + 3)] self.arr = arr self.fn = function self.make_tree(0, 0, len(arr) - 1) def make_tree(self, i, left, r): if left == r: self.segment[i] = self.arr[left] elif left < r: self.make_tree(2 * i + 1, left, int((left + r) / 2)) self.make_tree(2 * i + 2, int((left + r) / 2) + 1, r) self.segment[i] = self.fn( self.segment[2 * i + 1], self.segment[2 * i + 2] ) def __query(self, i, low, high, left, r): if left > high or r < low or low > high or left > r: return None if left <= low and r >= high: return self.segment[i] val1 = self.__query(2 * i + 1, low, int((low + high) / 2), left, r) val2 = self.__query( 2 * i + 2, int((low + high + 2) / 2), high, left, r ) print(low, high, " returned ", val1, val2) if val1 is not None: if val2 is not None: return self.fn(val1, val2) return val1 return val2 def query(self, low, high): return self.__query(0, 0, len(self.arr) - 1, low, high) """ Example - mytree = SegmentTree([2,4,5,3,4],max) mytree.query(2,4) mytree.query(0,3) ... mytree = SegmentTree([4,5,2,3,4,43,3],sum) mytree.query(1,8) ... """
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/segment_tree.py", "license": "MIT License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
keon/algorithms:algorithms/data_structures/separate_chaining_hash_table.py
""" 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) """ from __future__ import annotations class _Node: """Internal linked list node for chaining. Args: key: The key stored in this node. value: The value stored in this node. next_node: Reference to the next node in the chain. """ 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: """Hash table using separate chaining for collision resolution. Examples: >>> table = SeparateChainingHashTable() >>> table.put('hello', 'world') >>> len(table) 1 >>> table.get('hello') 'world' >>> del table['hello'] >>> table.get('hello') is None True """ _empty = None def __init__(self, size: int = 11) -> None: """Initialize the hash table. Args: size: Number of buckets. """ self.size = size self._len = 0 self._table: list[_Node | None] = [self._empty] * size def put(self, key: object, value: object) -> None: """Insert or update a key-value pair. Args: key: The key to insert. value: The value associated with the key. """ hash_ = self.hash(key) node_ = self._table[hash_] if node_ is self._empty: self._table[hash_] = _Node(key, value) else: while node_.next is not None: if node_.key == key: node_.value = value return node_ = node_.next node_.next = _Node(key, value) self._len += 1 def get(self, key: object) -> object | None: """Retrieve the value for a given key. Args: key: The key to look up. Returns: The associated value, or None if the key is not found. """ hash_ = self.hash(key) node_ = self._table[hash_] while node_ is not self._empty: if node_.key == key: return node_.value node_ = node_.next return None def del_(self, key: object) -> None: """Delete a key-value pair. Args: key: The key to delete. """ hash_ = self.hash(key) node_ = self._table[hash_] previous_node = None while node_ is not None: if node_.key == key: if previous_node is None: self._table[hash_] = node_.next else: previous_node.next = node_.next self._len -= 1 previous_node = node_ node_ = node_.next def hash(self, key: object) -> int: """Compute the bucket index for a key. Args: key: The key to hash. Returns: Bucket index. """ return hash(key) % self.size def __len__(self) -> int: return self._len def __getitem__(self, key: object) -> object | None: return self.get(key) def __delitem__(self, key: object) -> None: return self.del_(key) def __setitem__(self, key: object, value: object) -> None: self.put(key, value)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/separate_chaining_hash_table.py", "license": "MIT License", "lines": 113, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/data_structures/stack.py
""" 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/peek (amortized for ArrayStack) Space: O(n) """ from __future__ import annotations from abc import ABCMeta, abstractmethod from collections.abc import Iterator class AbstractStack(metaclass=ABCMeta): """Abstract base class for stack implementations.""" def __init__(self) -> None: self._top = -1 def __len__(self) -> int: return self._top + 1 def __str__(self) -> str: result = " ".join(map(str, self)) return "Top-> " + result def is_empty(self) -> bool: """Check if the stack is empty. Returns: True if the stack has no elements. """ return self._top == -1 @abstractmethod def __iter__(self) -> Iterator[object]: pass @abstractmethod def push(self, value: object) -> None: pass @abstractmethod def pop(self) -> object: pass @abstractmethod def peek(self) -> object: pass class ArrayStack(AbstractStack): """Stack implemented with a dynamic array. Examples: >>> s = ArrayStack() >>> s.push(1) >>> s.pop() 1 """ def __init__(self, size: int = 10) -> None: """Initialize with a fixed-size array. Args: size: Initial capacity of the underlying array. """ super().__init__() self._array: list[object | None] = [None] * size def __iter__(self) -> Iterator[object]: probe = self._top while True: if probe == -1: return yield self._array[probe] probe -= 1 def push(self, value: object) -> None: """Push a value onto the stack. Args: value: The value to push. """ self._top += 1 if self._top == len(self._array): self._expand() self._array[self._top] = value def pop(self) -> object: """Remove and return the top element. Returns: The top element. Raises: IndexError: If the stack is empty. """ if self.is_empty(): raise IndexError("Stack is empty") value = self._array[self._top] self._top -= 1 return value def peek(self) -> object: """Return the top element without removing it. Returns: The top element. Raises: IndexError: If the stack is empty. """ if self.is_empty(): raise IndexError("Stack is empty") return self._array[self._top] def _expand(self) -> None: """Double the size of the underlying array.""" self._array += [None] * len(self._array) class StackNode: """A single node in a linked-list-based stack.""" def __init__(self, value: object) -> None: self.value = value self.next: StackNode | None = None class LinkedListStack(AbstractStack): """Stack implemented with a singly linked list. Examples: >>> s = LinkedListStack() >>> s.push(1) >>> s.pop() 1 """ def __init__(self) -> None: super().__init__() self.head: StackNode | None = None def __iter__(self) -> Iterator[object]: probe = self.head while True: if probe is None: return yield probe.value probe = probe.next def push(self, value: object) -> None: """Push a value onto the stack. Args: value: The value to push. """ node = StackNode(value) node.next = self.head self.head = node self._top += 1 def pop(self) -> object: """Remove and return the top element. Returns: The top element. Raises: IndexError: If the stack is empty. """ if self.is_empty(): raise IndexError("Stack is empty") value = self.head.value self.head = self.head.next self._top -= 1 return value def peek(self) -> object: """Return the top element without removing it. Returns: The top element. Raises: IndexError: If the stack is empty. """ if self.is_empty(): raise IndexError("Stack is empty") return self.head.value
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/stack.py", "license": "MIT License", "lines": 150, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/data_structures/union_find.py
""" 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: Time: O(alpha(n)) amortized per operation (inverse Ackermann) Space: O(n) """ from __future__ import annotations class Union: """A Union-Find (Disjoint Set) data structure. Supports adding elements, finding set representatives, and merging sets. Uses union by size and path compression for near-constant amortized time. Examples: >>> uf = Union() >>> uf.add(1); uf.add(2); uf.add(3) >>> uf.unite(1, 2) >>> uf.root(1) == uf.root(2) True >>> uf.root(1) == uf.root(3) False """ def __init__(self) -> None: self.parents: dict[object, object] = {} self.size: dict[object, int] = {} self.count: int = 0 def add(self, element: object) -> None: """Add a new singleton set containing the given element. Args: element: The element to add. """ self.parents[element] = element self.size[element] = 1 self.count += 1 def root(self, element: object) -> object: """Find the root representative of the set containing element. Args: element: The element whose root to find. Returns: The root representative of the element's set. """ while element != self.parents[element]: self.parents[element] = self.parents[self.parents[element]] element = self.parents[element] return element def unite(self, element1: object, element2: object) -> None: """Merge the sets containing the two elements. Args: element1: An element in the first set. element2: An element in the second set. """ root1, root2 = self.root(element1), self.root(element2) if root1 == root2: return if self.size[root1] > self.size[root2]: root1, root2 = root2, root1 self.parents[root1] = root2 self.size[root2] += self.size[root1] self.count -= 1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/data_structures/union_find.py", "license": "MIT License", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/buy_sell_stock.py
""" 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) Space: O(1) max_profit_optimized: Time: O(n) Space: O(1) """ from __future__ import annotations def max_profit_naive(prices: list[int]) -> int: """Find maximum profit by checking all pairs of buy/sell days. Args: prices: List of stock prices per day. Returns: Maximum achievable profit (0 if no profitable trade exists). Examples: >>> max_profit_naive([7, 1, 5, 3, 6, 4]) 5 >>> max_profit_naive([7, 6, 4, 3, 1]) 0 """ 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]) -> int: """Find maximum profit using Kadane-style single pass. Args: prices: List of stock prices per day. Returns: Maximum achievable profit (0 if no profitable trade exists). Examples: >>> max_profit_optimized([7, 1, 5, 3, 6, 4]) 5 >>> max_profit_optimized([7, 6, 4, 3, 1]) 0 """ cur_max, max_so_far = 0, 0 for i in range(1, len(prices)): cur_max = max(0, cur_max + prices[i] - prices[i - 1]) max_so_far = max(max_so_far, cur_max) return max_so_far
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/buy_sell_stock.py", "license": "MIT License", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/climbing_stairs.py
""" 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_optimized: Time: O(n) Space: O(1) """ from __future__ import annotations def climb_stairs(steps: int) -> int: """Count distinct ways to climb n steps using a list-based DP approach. Args: steps: Number of steps in the staircase (positive integer). Returns: Number of distinct ways to reach the top. Examples: >>> climb_stairs(2) 2 >>> climb_stairs(10) 89 """ arr = [1, 1] for _ in range(1, steps): arr.append(arr[-1] + arr[-2]) return arr[-1] def climb_stairs_optimized(steps: int) -> int: """Count distinct ways to climb n steps using constant space. Args: steps: Number of steps in the staircase (positive integer). Returns: Number of distinct ways to reach the top. Examples: >>> climb_stairs_optimized(2) 2 >>> climb_stairs_optimized(10) 89 """ a_steps = b_steps = 1 for _ in range(steps): a_steps, b_steps = b_steps, a_steps + b_steps return a_steps
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/climbing_stairs.py", "license": "MIT License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/coin_change.py
""" 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 of coins Space: O(n) """ from __future__ import annotations def count(coins: list[int], value: int) -> int: """Find the number of coin combinations that add up to value. Args: coins: List of coin denominations. value: Target sum. Returns: Number of distinct combinations that sum to value. Examples: >>> count([1, 2, 3], 4) 4 >>> count([2, 5, 3, 6], 10) 5 """ 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]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/coin_change.py", "license": "MIT License", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/combination_sum.py
""" 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: O(target * n) Space: O(target) combination_sum_bottom_up: Time: O(target * n) Space: O(target) """ from __future__ import annotations def _helper_topdown(nums: list[int], target: int, dp: list[int]) -> int: """Recursive helper that fills the dp table top-down. Args: nums: Positive integer array without duplicates. target: Remaining target value. dp: Memoisation table. Returns: Number of combinations that sum to target. """ 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 result def combination_sum_topdown(nums: list[int], target: int) -> int: """Find number of combinations that add up to target (top-down DP). Args: nums: Positive integer array without duplicates. target: Target sum. Returns: Number of ordered combinations that sum to target. Examples: >>> combination_sum_topdown([1, 2, 3], 4) 7 """ dp = [-1] * (target + 1) dp[0] = 1 return _helper_topdown(nums, target, dp) def combination_sum_bottom_up(nums: list[int], target: int) -> int: """Find number of combinations that add up to target (bottom-up DP). Args: nums: Positive integer array without duplicates. target: Target sum. Returns: Number of ordered combinations that sum to target. Examples: >>> combination_sum_bottom_up([1, 2, 3], 4) 7 """ combs = [0] * (target + 1) combs[0] = 1 for i in range(0, len(combs)): for num in nums: if i - num >= 0: combs[i] += combs[i - num] return combs[target]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/combination_sum.py", "license": "MIT License", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/edit_distance.py
""" 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 two words Space: O(m * n) """ from __future__ import annotations def edit_distance(word_a: str, word_b: str) -> int: """Compute the edit distance between two words. Args: word_a: First word. word_b: Second word. Returns: Minimum number of single-character edits to transform word_a into word_b. Examples: >>> edit_distance('food', 'money') 4 >>> edit_distance('horse', 'ros') 3 """ 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[0][j] = j for i in range(1, length_a): for j in range(1, length_b): cost = 0 if word_a[i - 1] == word_b[j - 1] else 1 edit[i][j] = min( edit[i - 1][j] + 1, edit[i][j - 1] + 1, edit[i - 1][j - 1] + cost, ) return edit[-1][-1]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/edit_distance.py", "license": "MIT License", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/egg_drop.py
""" 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: O(n * k) """ from __future__ import annotations _INT_MAX = 32767 def egg_drop(n: int, k: int) -> int: """Find the minimum number of trials to identify the critical floor. Args: n: Number of eggs. k: Number of floors. Returns: Minimum number of trials in the worst case. Examples: >>> egg_drop(1, 2) 2 >>> egg_drop(2, 6) 3 """ 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 range(2, n + 1): for j in range(2, k + 1): egg_floor[i][j] = _INT_MAX for x in range(1, j + 1): res = 1 + max(egg_floor[i - 1][x - 1], egg_floor[i][j - x]) if res < egg_floor[i][j]: egg_floor[i][j] = res return egg_floor[n][k]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/egg_drop.py", "license": "MIT License", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/fib.py
""" 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) fib_list: Time: O(n) Space: O(n) fib_iter: Time: O(n) Space: O(1) """ from __future__ import annotations def fib_recursive(n: int) -> int: """Compute the n-th Fibonacci number recursively. Args: n: Non-negative integer index into the Fibonacci sequence. Returns: The n-th Fibonacci number. Examples: >>> fib_recursive(10) 55 """ 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: """Compute the n-th Fibonacci number using a list-based DP table. Args: n: Non-negative integer index into the Fibonacci sequence. Returns: The n-th Fibonacci number. Examples: >>> fib_list(10) 55 """ assert n >= 0, "n must be a positive integer" list_results = [0, 1] for i in range(2, n + 1): list_results.append(list_results[i - 1] + list_results[i - 2]) return list_results[n] def fib_iter(n: int) -> int: """Compute the n-th Fibonacci number iteratively with constant space. Args: n: Non-negative integer index into the Fibonacci sequence. Returns: The n-th Fibonacci number. Examples: >>> fib_iter(10) 55 """ assert n >= 0, "n must be positive integer" fib_1 = 0 fib_2 = 1 res = 0 if n <= 1: return n for _ in range(n - 1): res = fib_1 + fib_2 fib_1 = fib_2 fib_2 = res return res
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/fib.py", "license": "MIT License", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/hosoya_triangle.py
""" 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) Space: O(n) (call stack depth) """ from __future__ import annotations def hosoya(height: int, width: int) -> int: """Compute a single entry in the Hosoya triangle. Args: height: Row index (0-based). width: Column index (0-based). Returns: The value at position (height, width) in the Hosoya triangle. Examples: >>> hosoya(4, 2) 4 """ 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: return hosoya(height - 1, width - 1) + hosoya(height - 2, width - 2) return 0 def hosoya_testing(height: int) -> list[int]: """Generate a flat list of all Hosoya triangle values up to given height. Args: height: Number of rows to generate. Returns: Flat list of triangle values row by row. Examples: >>> hosoya_testing(1) [1] """ res = [] for i in range(height): for j in range(i + 1): res.append(hosoya(i, j)) return res
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/hosoya_triangle.py", "license": "MIT License", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/house_robber.py
""" 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 house_robber(houses: list[int]) -> int: """Compute the maximum robbery amount without hitting adjacent houses. Args: houses: List of non-negative integers representing money in each house. Returns: Maximum amount that can be robbed. Examples: >>> house_robber([1, 2, 16, 3, 15, 3, 12, 1]) 44 """ last, now = 0, 0 for house in houses: last, now = now, max(last + house, now) return now
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/house_robber.py", "license": "MIT License", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/int_divide.py
""" 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__ import annotations def int_divide(decompose: int) -> int: """Count the number of partitions of a positive integer. Args: decompose: The positive integer to partition. Returns: Number of distinct partitions. Examples: >>> int_divide(4) 5 >>> int_divide(7) 15 """ 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] elif i == j: arr[i][j] = 1 + arr[i][j - 1] else: arr[i][j] = arr[i][j - 1] + arr[i - j][j] return arr[decompose][decompose]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/int_divide.py", "license": "MIT License", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/job_scheduling.py
""" 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 __future__ import annotations class Job: """Represents a job with start time, finish time, and profit.""" 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: """Find the latest non-conflicting job before start_index. Args: job: List of jobs sorted by finish time. start_index: Index of the current job. Returns: Index of the latest compatible job, or -1 if none exists. """ left = 0 right = start_index - 1 while left <= right: mid = (left + right) // 2 if job[mid].finish <= job[start_index].start: if job[mid + 1].finish <= job[start_index].start: left = mid + 1 else: return mid else: right = mid - 1 return -1 def schedule(job: list[Job]) -> int: """Find the maximum profit from non-overlapping jobs. Args: job: List of Job objects. Returns: Maximum achievable profit. Examples: >>> schedule([Job(1, 3, 2), Job(2, 3, 4)]) 4 """ job = sorted(job, key=lambda j: j.finish) length = len(job) table = [0 for _ in range(length)] table[0] = job[0].profit for i in range(1, length): incl_prof = job[i].profit pos = _binary_search(job, i) if pos != -1: incl_prof += table[pos] table[i] = max(incl_prof, table[i - 1]) return table[length - 1]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/job_scheduling.py", "license": "MIT License", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/k_factor.py
""" 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: Time: O(length^2) Space: O(length^2) """ from __future__ import annotations def find_k_factor(length: int, k_factor: int) -> int: """Count strings of given length with exactly k_factor 'abba' substrings. Args: length: Length of the strings to consider. k_factor: Required number of 'abba' substrings. Returns: Number of strings satisfying the K-factor constraint. Examples: >>> find_k_factor(4, 1) 1 >>> find_k_factor(7, 1) 70302 """ 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][0][2] = 0 mat[1][0][3] = 25 for i in range(2, length + 1): for j in range((length - 1) // 3 + 2): if j == 0: mat[i][j][0] = mat[i - 1][j][0] + mat[i - 1][j][1] + mat[i - 1][j][3] mat[i][j][1] = mat[i - 1][j][0] mat[i][j][2] = mat[i - 1][j][1] mat[i][j][3] = ( mat[i - 1][j][0] * 24 + mat[i - 1][j][1] * 24 + mat[i - 1][j][2] * 25 + mat[i - 1][j][3] * 25 ) elif 3 * j + 1 < i: mat[i][j][0] = ( mat[i - 1][j][0] + mat[i - 1][j][1] + mat[i - 1][j][3] + mat[i - 1][j - 1][2] ) mat[i][j][1] = mat[i - 1][j][0] mat[i][j][2] = mat[i - 1][j][1] mat[i][j][3] = ( mat[i - 1][j][0] * 24 + mat[i - 1][j][1] * 24 + mat[i - 1][j][2] * 25 + mat[i - 1][j][3] * 25 ) elif 3 * j + 1 == i: mat[i][j][0] = 1 mat[i][j][1] = 0 mat[i][j][2] = 0 mat[i][j][3] = 0 else: mat[i][j][0] = 0 mat[i][j][1] = 0 mat[i][j][2] = 0 mat[i][j][3] = 0 return sum(mat[length][k_factor])
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/k_factor.py", "license": "MIT License", "lines": 72, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
keon/algorithms:algorithms/dynamic_programming/knapsack.py
""" 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 capacity Space: O(m) """ from __future__ import annotations class Item: """Represents an item with a value and weight.""" def __init__(self, value: int, weight: int) -> None: self.value = value self.weight = weight def get_maximum_value(items: list[Item], capacity: int) -> int: """Compute the maximum value achievable within the knapsack capacity. Args: items: List of Item objects with value and weight attributes. capacity: Maximum weight the knapsack can hold. Returns: Maximum total value that fits in the knapsack. Examples: >>> get_maximum_value([Item(60, 5), Item(50, 3), Item(70, 4), Item(30, 2)], 5) 80 """ dp = [0] * (capacity + 1) for item in items: for cur_weight in reversed(range(item.weight, capacity + 1)): dp[cur_weight] = max( dp[cur_weight], item.value + dp[cur_weight - item.weight] ) return dp[capacity]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/knapsack.py", "license": "MIT License", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/longest_common_subsequence.py
""" 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_subsequence(s_1: str, s_2: str) -> int: """Compute the length of the longest common subsequence of two strings. Args: s_1: First string. s_2: Second string. Returns: Length of the longest common subsequence. Examples: >>> longest_common_subsequence('abcdgh', 'aedfhr') 3 """ 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[i - 1] == s_2[j - 1]: mat[i][j] = mat[i - 1][j - 1] + 1 else: mat[i][j] = max(mat[i - 1][j], mat[i][j - 1]) return mat[m][n]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/longest_common_subsequence.py", "license": "MIT License", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/longest_increasing.py
""" 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) longest_increasing_subsequence_optimized: Time: O(n * log(x)) where x is the max element Space: O(x) longest_increasing_subsequence_optimized2: Time: O(n * log(n)) Space: O(n) """ from __future__ import annotations def longest_increasing_subsequence(sequence: list[int]) -> int: """Find length of the longest increasing subsequence using O(n^2) DP. Args: sequence: List of integers. Returns: Length of the longest strictly increasing subsequence. Examples: >>> longest_increasing_subsequence([10, 9, 2, 5, 3, 7, 101, 18]) 4 """ 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], counts[j] + 1) return max(counts) def longest_increasing_subsequence_optimized(sequence: list[int]) -> int: """Find length of LIS using a segment tree for O(n*log(x)) time. Args: sequence: List of integers. Returns: Length of the longest strictly increasing subsequence. Examples: >>> longest_increasing_subsequence_optimized([10, 9, 2, 5, 3, 7, 101, 18]) 4 """ max_val = max(sequence) tree = [0] * (max_val << 2) def _update(pos: int, left: int, right: int, target: int, vertex: int) -> None: if left == right: tree[pos] = vertex return mid = (left + right) >> 1 if target <= mid: _update(pos << 1, left, mid, target, vertex) else: _update((pos << 1) | 1, mid + 1, right, target, vertex) tree[pos] = max(tree[pos << 1], tree[(pos << 1) | 1]) def _get_max(pos: int, left: int, right: int, start: int, end: int) -> int: if left > end or right < start: return 0 if left >= start and right <= end: return tree[pos] mid = (left + right) >> 1 return max( _get_max(pos << 1, left, mid, start, end), _get_max((pos << 1) | 1, mid + 1, right, start, end), ) ans = 0 for element in sequence: cur = _get_max(1, 0, max_val, 0, element - 1) + 1 ans = max(ans, cur) _update(1, 0, max_val, element, cur) return ans def longest_increasing_subsequence_optimized2(sequence: list[int]) -> int: """Find length of LIS using coordinate-compressed segment tree for O(n*log(n)). Args: sequence: List of integers. Returns: Length of the longest strictly increasing subsequence. Examples: >>> longest_increasing_subsequence_optimized2([10, 9, 2, 5, 3, 7, 101, 18]) 4 """ length = len(sequence) tree = [0] * (length << 2) sorted_seq = sorted((x, -i) for i, x in enumerate(sequence)) def _update(pos: int, left: int, right: int, target: int, vertex: int) -> None: if left == right: tree[pos] = vertex return mid = (left + right) >> 1 if target <= mid: _update(pos << 1, left, mid, target, vertex) else: _update((pos << 1) | 1, mid + 1, right, target, vertex) tree[pos] = max(tree[pos << 1], tree[(pos << 1) | 1]) def _get_max(pos: int, left: int, right: int, start: int, end: int) -> int: if left > end or right < start: return 0 if left >= start and right <= end: return tree[pos] mid = (left + right) >> 1 return max( _get_max(pos << 1, left, mid, start, end), _get_max((pos << 1) | 1, mid + 1, right, start, end), ) ans = 0 for tup in sorted_seq: i = -tup[1] cur = _get_max(1, 0, length - 1, 0, i - 1) + 1 ans = max(ans, cur) _update(1, 0, length - 1, i, cur) return ans
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/longest_increasing.py", "license": "MIT License", "lines": 111, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
keon/algorithms:algorithms/dynamic_programming/matrix_chain_order.py
""" 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 __future__ import annotations _INF = float("inf") def matrix_chain_order(array: list[int]) -> tuple[list[list[int]], list[list[int]]]: """Compute minimum multiplication cost and optimal split positions. Args: array: List of matrix dimensions where matrix i has dimensions array[i-1] x array[i]. Returns: A tuple of (cost_matrix, split_matrix) where cost_matrix[i][j] holds the minimum cost and split_matrix[i][j] holds the optimal split point. Examples: >>> m, s = matrix_chain_order([30, 35, 15, 5, 10, 20, 25]) >>> m[1][6] 15125 """ 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 in range(1, n - chain_length + 1): b = a + chain_length - 1 matrix[a][b] = _INF for c in range(a, b): cost = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: matrix[a][b] = cost sol[a][b] = c return matrix, sol
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/matrix_chain_order.py", "license": "MIT License", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/max_product_subarray.py
""" 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: Time: O(n) Space: O(1) """ from __future__ import annotations from functools import reduce def max_product(nums: list[int]) -> int: """Find the maximum product of a contiguous subarray. Args: nums: List of integers (containing at least one number). Returns: Largest product among all contiguous subarrays. Examples: >>> max_product([2, 3, -2, 4]) 6 """ 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, lmax) return gmax def subarray_with_max_product(arr: list[int]) -> tuple[int, list[int]]: """Find the maximum product subarray and return the product and subarray. Args: arr: List of positive or negative integers. Returns: A tuple of (max_product, subarray) where subarray is the contiguous slice that achieves the maximum product. Examples: >>> subarray_with_max_product([-2, -3, 6, 0, -7, -5]) (36, [-2, -3, 6]) """ length = len(arr) product_so_far = max_product_end = 1 max_start_i = 0 so_far_start_i = so_far_end_i = 0 all_negative_flag = True for i in range(length): max_product_end *= arr[i] if arr[i] > 0: all_negative_flag = False if max_product_end <= 0: max_product_end = arr[i] max_start_i = i if product_so_far <= max_product_end: product_so_far = max_product_end so_far_end_i = i so_far_start_i = max_start_i if all_negative_flag: product = reduce(lambda x, y: x * y, arr) return product, arr return product_so_far, arr[so_far_start_i : so_far_end_i + 1]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/max_product_subarray.py", "license": "MIT License", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/max_subarray.py
""" 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[int]) -> int: """Find the maximum sum of a contiguous subarray using Kadane's algorithm. Args: array: List of integers (containing at least one number). Returns: Largest sum among all contiguous subarrays. Examples: >>> max_subarray([1, 2, -3, 4, 5, -7, 23]) 25 """ 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
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/max_subarray.py", "license": "MIT License", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/min_cost_path.py
""" 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) Space: O(n) """ from __future__ import annotations _INF = float("inf") def min_cost(cost: list[list[int]]) -> int: """Compute the minimum cost to reach the last station from station 0. Args: cost: Square matrix where cost[i][j] is the travel cost from station i to station j (for i < j). Returns: Minimum cost to reach station N-1 from station 0. Examples: >>> min_cost([[0, 15, 80, 90], [-1, 0, 40, 50], ... [-1, -1, 0, 70], [-1, -1, -1, 0]]) 65 """ 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]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/min_cost_path.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/num_decodings.py
""" 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 """ from __future__ import annotations def num_decodings(enc_mes: str) -> int: """Count decoding ways using constant-space iteration. Args: enc_mes: String of digits representing the encoded message. Returns: Total number of ways to decode the message. Examples: >>> num_decodings("12") 2 >>> num_decodings("226") 3 """ 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 if int(enc_mes[i - 1 : i + 1]) < 27 and enc_mes[i - 1] != "0" else 0 ) last_two_chars = last_char last_char = last + last_two return last_char def num_decodings2(enc_mes: str) -> int: """Count decoding ways using a stack-based approach. Args: enc_mes: String of digits representing the encoded message. Returns: Total number of ways to decode the message. Examples: >>> num_decodings2("12") 2 >>> num_decodings2("226") 3 """ if not enc_mes or enc_mes.startswith("0"): return 0 stack = [1, 1] for i in range(1, len(enc_mes)): if enc_mes[i] == "0": if enc_mes[i - 1] == "0" or enc_mes[i - 1] > "2": return 0 stack.append(stack[-2]) elif 9 < int(enc_mes[i - 1 : i + 1]) < 27: stack.append(stack[-2] + stack[-1]) else: stack.append(stack[-1]) return stack[-1]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/num_decodings.py", "license": "MIT License", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/planting_trees.py
""" 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: O(n^2) """ from __future__ import annotations from math import sqrt def planting_trees(trees: list[int], length: int, width: int) -> float: """Compute the minimum distance to rearrange trees to valid positions. Args: trees: Sorted list of current tree positions along the road. length: Length of the road. width: Width of the road. Returns: Minimum total distance the trees must be moved. Examples: >>> planting_trees([0, 1, 10, 10], 10, 1) 2.414213562373095 """ 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(n_pairs)] cmatrix = [[0 for _ in range(n_pairs + 1)] for _ in range(n_pairs + 1)] for r_i in range(1, n_pairs + 1): cmatrix[r_i][0] = cmatrix[r_i - 1][0] + sqrt( width + abs(trees[r_i] - target_locations[r_i - 1]) ** 2 ) for l_i in range(1, n_pairs + 1): cmatrix[0][l_i] = cmatrix[0][l_i - 1] + abs( trees[l_i] - target_locations[l_i - 1] ) for r_i in range(1, n_pairs + 1): for l_i in range(1, n_pairs + 1): cmatrix[r_i][l_i] = min( cmatrix[r_i - 1][l_i] + sqrt(width + (trees[l_i + r_i] - target_locations[r_i - 1]) ** 2), cmatrix[r_i][l_i - 1] + abs(trees[l_i + r_i] - target_locations[l_i - 1]), ) return cmatrix[n_pairs][n_pairs]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/planting_trees.py", "license": "MIT License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/regex_matching.py
""" 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) Space: O(m * n) """ from __future__ import annotations def is_match(str_a: str, str_b: str) -> bool: """Determine whether str_a matches the pattern str_b. Args: str_a: Input string. str_b: Pattern string (may contain '.' and '*'). Returns: True if str_a fully matches str_b, False otherwise. Examples: >>> is_match("aa", "a") False >>> is_match("aa", "a*") True """ 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 == "*" for i, char_a in enumerate(str_a, 1): for j, char_b in enumerate(str_b, 1): if char_b != "*": matches[i][j] = matches[i - 1][j - 1] and char_b in (char_a, ".") else: matches[i][j] |= matches[i][j - 2] if char_a == str_b[j - 2] or str_b[j - 2] == ".": matches[i][j] |= matches[i - 1][j] return matches[-1][-1]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/regex_matching.py", "license": "MIT License", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/rod_cut.py
""" 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) """ from __future__ import annotations _INT_MIN = -32767 def cut_rod(price: list[int]) -> int: """Compute the maximum obtainable value by cutting a rod optimally. Args: price: List where price[i] is the price of a piece of length i+1. Returns: Maximum revenue from cutting and selling the rod. Examples: >>> cut_rod([1, 5, 8, 9, 10, 17, 17, 20]) 22 """ 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 return val[n]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/rod_cut.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/dynamic_programming/word_break.py
""" 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 def word_break(word: str, word_dict: set[str]) -> bool: """Determine if word can be segmented into dictionary words. Args: word: The string to segment. word_dict: Set of valid dictionary words. Returns: True if word can be segmented, False otherwise. Examples: >>> word_break("leetcode", {"leet", "code"}) True >>> word_break("catsandog", {"cats", "dog", "sand", "and", "cat"}) False """ 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 break return dp_array[-1]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/dynamic_programming/word_break.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/all_factors.py
""" 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 density) Space: O(log n) """ from __future__ import annotations def get_factors(n: int) -> list[list[int]]: """Return all factor combinations of *n* using recursion. Args: n: The number to factorise. Returns: List of factor lists. Examples: >>> get_factors(12) [[2, 6], [2, 2, 3], [3, 4]] """ 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)],) _factor(n / i, i, combi + [i], res) i += 1 return res return _factor(n, 2, [], []) def get_factors_iterative1(n: int) -> list[list[int]]: """Return all factor combinations using an explicit stack. Args: n: The number to factorise. Returns: List of factor lists. Examples: >>> get_factors_iterative1(12) [[2, 6], [3, 4], [2, 2, 3]] """ todo: list[tuple[int, int, list[int]]] = [(n, 2, [])] res: list[list[int]] = [] while todo: n, i, combi = todo.pop() while i * i <= n: if n % i == 0: res += (combi + [i, n // i],) todo.append((n // i, i, combi + [i])) i += 1 return res def get_factors_iterative2(n: int) -> list[list[int]]: """Return all factor combinations using a stack-based approach. Args: n: The number to factorise. Returns: List of factor lists. Examples: >>> get_factors_iterative2(12) [[2, 2, 3], [2, 6], [3, 4]] """ ans: list[list[int]] = [] stack: list[int] = [] x = 2 while True: if x > n // x: if not stack: return ans ans.append(stack + [n]) x = stack.pop() n *= x x += 1 elif n % x == 0: stack.append(x) n //= x else: x += 1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/all_factors.py", "license": "MIT License", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/count_islands_bfs.py
""" 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: Time: O(M * N) Space: O(M * N) """ from __future__ import annotations def count_islands(grid: list[list[int]]) -> int: """Return the number of islands in *grid*. Args: grid: 2D matrix of 0s and 1s. Returns: Number of connected components of 1s. Examples: >>> count_islands([[1, 0], [0, 1]]) 2 """ 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: list[tuple[int, int]] = [] for i in range(row): for j, num in enumerate(grid[i]): if num == 1 and visited[i][j] != 1: visited[i][j] = 1 queue.append((i, j)) while queue: x, y = queue.pop(0) for k in range(len(directions)): nx_x = x + directions[k][0] nx_y = y + directions[k][1] if (0 <= nx_x < row and 0 <= nx_y < col and visited[nx_x][nx_y] != 1 and grid[nx_x][nx_y] == 1): queue.append((nx_x, nx_y)) visited[nx_x][nx_y] = 1 num_islands += 1 return num_islands
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/count_islands_bfs.py", "license": "MIT License", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/count_islands_dfs.py
""" 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 __future__ import annotations def num_islands(grid: list[list[int]]) -> int: """Return the number of islands in *grid*. Args: grid: 2D matrix of 0s and 1s (modified in place during traversal). Returns: Number of connected components of 1s. Examples: >>> num_islands([[1, 0], [0, 1]]) 2 """ 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: int) -> None: """Flood-fill from (i, j), marking visited cells as 0. Args: grid: The grid (modified in place). i: Row index. j: Column index. """ if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]): return if grid[i][j] != 1: return grid[i][j] = 0 _dfs(grid, i + 1, j) _dfs(grid, i - 1, j) _dfs(grid, i, j + 1) _dfs(grid, i, j - 1)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/count_islands_dfs.py", "license": "MIT License", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/count_islands_unionfind.py
""" 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 Complexity: Time: O(m * alpha(m)) where m is number of positions Space: O(m) """ from __future__ import annotations from algorithms.data_structures.union_find import Union def num_islands(positions: list[list[int]]) -> list[int]: """Count islands after each addLand operation. Given a sequence of positions on a 2D grid, each operation turns a water cell into land. After each operation, count the number of distinct islands (connected components of land cells). Args: positions: A list of [row, col] pairs indicating land additions. Returns: A list of island counts, one per operation. Examples: >>> num_islands([[0, 0], [0, 1], [1, 2], [2, 1]]) [1, 1, 2, 3] """ result: list[int] = [] islands = Union() for position in map(tuple, positions): islands.add(position) for delta in (0, 1), (0, -1), (1, 0), (-1, 0): adjacent = (position[0] + delta[0], position[1] + delta[1]) if adjacent in islands.parents: islands.unite(position, adjacent) result.append(islands.count) return result
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/count_islands_unionfind.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/maze_search_bfs.py
""" 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 annotations from collections import deque def maze_search(maze: list[list[int]]) -> int: """Return the shortest path length in *maze*, or -1 if unreachable. Args: maze: 2D grid where 1 = passable, 0 = blocked. Returns: Minimum steps from (0,0) to (height-1, width-1), or -1. Examples: >>> maze_search([[1, 1], [1, 1]]) 2 >>> maze_search([[1, 0], [0, 1]]) -1 """ 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, 0)] height, width = len(maze), len(maze[0]) target_x, target_y = height - 1, width - 1 queue = deque([(initial_x, initial_y, 0)]) is_visited = [[unvisited for _ in range(width)] for _ in range(height)] is_visited[initial_x][initial_y] = visited while queue: x, y, steps = queue.popleft() if x == target_x and y == target_y: return steps for dx, dy in directions: new_x = x + dx new_y = y + dy if not (0 <= new_x < height and 0 <= new_y < width): continue if maze[new_x][new_y] == allowed and is_visited[new_x][new_y] == unvisited: queue.append((new_x, new_y, steps + 1)) is_visited[new_x][new_y] = visited return -1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/maze_search_bfs.py", "license": "MIT License", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/maze_search_dfs.py
""" 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) Space: O(M * N) """ from __future__ import annotations def find_path(maze: list[list[int]]) -> int: """Return the shortest path length in *maze*, or -1 if unreachable. Args: maze: 2D grid where 1 = passable, 0 = blocked. Returns: Minimum steps from (0,0) to (height-1, width-1), or -1. Examples: >>> find_path([[1, 1], [1, 1]]) 2 """ cnt = _dfs(maze, 0, 0, 0, -1) return cnt def _dfs( maze: list[list[int]], i: int, j: int, depth: int, cnt: int, ) -> int: """Recursive DFS helper for maze search. Args: maze: The grid (modified temporarily during recursion). i: Current row. j: Current column. depth: Current path length. cnt: Best path length found so far (-1 = none). Returns: Updated best path length. """ directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] row = len(maze) col = len(maze[0]) if i == row - 1 and j == col - 1: if cnt == -1: cnt = depth else: if cnt > depth: cnt = depth return cnt maze[i][j] = 0 for k in range(len(directions)): nx_i = i + directions[k][0] nx_j = j + directions[k][1] if 0 <= nx_i < row and 0 <= nx_j < col and maze[nx_i][nx_j] == 1: cnt = _dfs(maze, nx_i, nx_j, depth + 1, cnt) maze[i][j] = 1 return cnt
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/maze_search_dfs.py", "license": "MIT License", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/pacific_atlantic.py
""" 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(M * N) Space: O(M * N) """ from __future__ import annotations def pacific_atlantic(matrix: list[list[int]]) -> list[list[int]]: """Return coordinates where water can flow to both oceans. Args: matrix: Height map. Returns: List of [row, col] pairs. Examples: >>> pacific_atlantic([[1]]) [[0, 0]] """ 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 = [[False for _ in range(n)] for _ in range(m)] for i in range(n): _dfs(pacific, matrix, float("-inf"), i, 0) _dfs(atlantic, matrix, float("-inf"), i, m - 1) for i in range(m): _dfs(pacific, matrix, float("-inf"), 0, i) _dfs(atlantic, matrix, float("-inf"), n - 1, i) for i in range(n): for j in range(m): if pacific[i][j] and atlantic[i][j]: res.append([i, j]) return res def _dfs( grid: list[list[bool]], matrix: list[list[int]], height: float, i: int, j: int, ) -> None: """Mark cells reachable from (i, j) flowing uphill. Args: grid: Reachability matrix (modified in place). matrix: Height map. height: Previous cell height. i: Row index. j: Column index. """ if i < 0 or i >= len(matrix) or j < 0 or j >= len(matrix[0]): return if grid[i][j] or matrix[i][j] < height: return grid[i][j] = True _dfs(grid, matrix, matrix[i][j], i - 1, j) _dfs(grid, matrix, matrix[i][j], i + 1, j) _dfs(grid, matrix, matrix[i][j], i, j - 1) _dfs(grid, matrix, matrix[i][j], i, j + 1)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/pacific_atlantic.py", "license": "MIT License", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/shortest_distance_from_all_buildings.py
""" Shortest Distance from All Buildings Given a 2D grid with buildings (1), empty land (0) and obstacles (2), find the empty land with the smallest total distance to all buildings. Reference: https://leetcode.com/problems/shortest-distance-from-all-buildings/ Complexity: Time: O(B * M * N) where B is the number of buildings Space: O(M * N) """ from __future__ import annotations def shortest_distance(grid: list[list[int]]) -> int: """Return the minimum total distance from an empty cell to all buildings. Args: grid: 2D grid (0 = empty, 1 = building, 2 = obstacle). Returns: Minimum sum of distances, or -1 if impossible. Examples: >>> shortest_distance([[1, 0, 1]]) 2 """ if not grid or not grid[0]: return -1 matrix = [[[0, 0] for _ in range(len(grid[0]))] for _ in range(len(grid))] count = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: _bfs(grid, matrix, i, j, count) count += 1 res = float("inf") for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j][1] == count: res = min(res, matrix[i][j][0]) return res if res != float("inf") else -1 def _bfs( grid: list[list[int]], matrix: list[list[list[int]]], i: int, j: int, count: int, ) -> None: """BFS from building at (i, j), updating *matrix* distances. Args: grid: The original grid. matrix: Accumulator for [total_distance, visit_count]. i: Row of the building. j: Column of the building. count: Number of buildings visited so far. """ q: list[tuple[int, int, int]] = [(i, j, 0)] while q: i, j, step = q.pop(0) for k, col in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]: if ( 0 <= k < len(grid) and 0 <= col < len(grid[0]) and matrix[k][col][1] == count and grid[k][col] == 0 ): matrix[k][col][0] += step + 1 matrix[k][col][1] = count + 1 q.append((k, col, step + 1))
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/shortest_distance_from_all_buildings.py", "license": "MIT License", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/sudoku_solver.py
""" 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 cells)) worst case Space: O(N^2) """ from __future__ import annotations class Sudoku: """A Sudoku board solver.""" def __init__( self, board: list[list[str]], row: int, col: int, ) -> None: """Initialise the solver with the given board. Args: board: 2D list of digits or '.' for empty cells. row: Number of rows. col: Number of columns. """ self.board = board self.row = row self.col = col self.val = self._possible_values() def _possible_values(self) -> dict[tuple[int, int], list[str]]: """Compute possible values for each empty cell. Returns: Mapping from (row, col) to list of candidate digits. """ a = "123456789" d: dict[tuple[str, int] | tuple[int, int], list[str]] = {} val: dict[tuple[int, int], list[str]] = {} for i in range(self.row): for j in range(self.col): ele = self.board[i][j] if ele != ".": d[("r", i)] = d.get(("r", i), []) + [ele] d[("c", j)] = d.get(("c", j), []) + [ele] d[(i // 3, j // 3)] = d.get((i // 3, j // 3), []) + [ele] else: val[(i, j)] = [] for i, j in val: inval = ( d.get(("r", i), []) + d.get(("c", j), []) + d.get((i / 3, j / 3), []) ) val[(i, j)] = [n for n in a if n not in inval] return val def solve(self) -> bool: """Attempt to solve the board in place. Returns: True if a solution was found. """ if len(self.val) == 0: return True kee = min(self.val.keys(), key=lambda x: len(self.val[x])) nums = self.val[kee] for n in nums: update: dict[tuple[int, int], str | list[str]] = {kee: self.val[kee]} if self._valid_one(n, kee, update) and self.solve(): return True self._undo(kee, update) return False def _valid_one( self, n: str, kee: tuple[int, int], update: dict[tuple[int, int], str | list[str]], ) -> bool: """Place digit *n* at *kee* and propagate constraints. Args: n: Digit to place. kee: (row, col) coordinate. update: Undo log (modified in place). Returns: True if placement is valid. """ self.board[kee[0]][kee[1]] = n del self.val[kee] i, j = kee for ind in list(self.val.keys()): if n in self.val[ind] and ( ind[0] == i or ind[1] == j or (ind[0] / 3, ind[1] / 3) == (i / 3, j / 3) ): update[ind] = n self.val[ind].remove(n) if len(self.val[ind]) == 0: return False return True def _undo( self, kee: tuple[int, int], update: dict[tuple[int, int], str | list[str]], ) -> None: """Revert the placement at *kee* using *update*. Args: kee: (row, col) coordinate. update: Undo log. """ self.board[kee[0]][kee[1]] = "." for k in update: if k not in self.val: self.val[k] = update[k] else: self.val[k].append(update[k]) def __str__(self) -> str: """Return a string representation of the board. Returns: Formatted board string. """ resp = "" for i in range(self.row): for j in range(self.col): resp += f" {self.board[i][j]} " resp += "\n" return resp
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/sudoku_solver.py", "license": "MIT License", "lines": 121, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
keon/algorithms:algorithms/graph/topological_sort_bfs.py
""" Topological Sort (Kahn's Algorithm / BFS) Computes a topological ordering of a directed acyclic graph. Raises ValueError when a cycle is detected. Reference: https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm Complexity: Time: O(V + E) Space: O(V + E) """ from __future__ import annotations from collections import defaultdict, deque def topological_sort(vertices: int, edges: list[tuple[int, int]]) -> list[int]: """Return a topological ordering of the vertices. Args: vertices: Number of vertices (labelled 0 .. vertices-1). edges: Directed edges as (u, v) meaning u -> v. Returns: List of vertices in topological order. Raises: ValueError: If the graph contains a cycle. Examples: >>> topological_sort(3, [(0, 1), (1, 2)]) [0, 1, 2] """ graph: dict[int, list[int]] = defaultdict(list) in_degree = [0] * vertices for u, v in edges: graph[u].append(v) in_degree[v] += 1 queue: deque[int] = deque() for i in range(vertices): if in_degree[i] == 0: queue.append(i) sorted_order: list[int] = [] processed = 0 while queue: node = queue.popleft() sorted_order.append(node) processed += 1 for neighbor in graph[node]: in_degree[neighbor] -= 1 if in_degree[neighbor] == 0: queue.append(neighbor) if processed != vertices: raise ValueError("Cycle detected, topological sort failed") return sorted_order
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/topological_sort_bfs.py", "license": "MIT License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/topological_sort_dfs.py
""" 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.wikipedia.org/wiki/Topological_sorting Complexity: Time: O(V + E) Space: O(V) """ from __future__ import annotations _GRAY, _BLACK = 0, 1 def top_sort_recursive(graph: dict[str, list[str]]) -> list[str]: """Return a topological ordering of *graph* using recursive DFS. Args: graph: Adjacency-list representation of a directed graph. Returns: A list of vertices in topological order. Raises: ValueError: If the graph contains a cycle. Examples: >>> top_sort_recursive({'a': ['b'], 'b': []}) ['b', 'a'] """ order: list[str] = [] enter = set(graph) state: dict[str, int] = {} def _dfs(node: str) -> None: state[node] = _GRAY for neighbour in graph.get(node, ()): neighbour_state = state.get(neighbour) if neighbour_state == _GRAY: raise ValueError("cycle") if neighbour_state == _BLACK: continue enter.discard(neighbour) _dfs(neighbour) order.append(node) state[node] = _BLACK while enter: _dfs(enter.pop()) return order def top_sort(graph: dict[str, list[str]]) -> list[str]: """Return a topological ordering of *graph* using an iterative approach. Args: graph: Adjacency-list representation of a directed graph. Returns: A list of vertices in topological order. Raises: ValueError: If the graph contains a cycle. Examples: >>> top_sort({'a': ['b'], 'b': []}) ['b', 'a'] """ order: list[str] = [] enter = set(graph) state: dict[str, int] = {} def _is_ready(node: str) -> bool: neighbours = graph.get(node, ()) if len(neighbours) == 0: return True for neighbour in neighbours: neighbour_state = state.get(neighbour) if neighbour_state == _GRAY: raise ValueError("cycle") if neighbour_state != _BLACK: return False return True while enter: node = enter.pop() stack: list[str] = [] while True: state[node] = _GRAY stack.append(node) for neighbour in graph.get(node, ()): neighbour_state = state.get(neighbour) if neighbour_state == _GRAY: raise ValueError("cycle") if neighbour_state == _BLACK: continue enter.discard(neighbour) stack.append(neighbour) while stack and _is_ready(stack[-1]): node = stack.pop() order.append(node) state[node] = _BLACK if len(stack) == 0: break node = stack.pop() return order
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/topological_sort_dfs.py", "license": "MIT License", "lines": 91, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
keon/algorithms:algorithms/graph/walls_and_gates.py
""" Walls and Gates Fill each empty room (INF) with the distance to its nearest gate (0). Walls are represented by -1. Reference: https://leetcode.com/problems/walls-and-gates/ Complexity: Time: O(M * N) Space: O(M * N) recursion stack """ from __future__ import annotations def walls_and_gates(rooms: list[list[int]]) -> None: """Fill *rooms* in place with distances to nearest gates. Args: rooms: 2D grid (-1 = wall, 0 = gate, INF = empty room). Examples: >>> r = [[float('inf'), 0]]; walls_and_gates(r); r [[1, 0]] """ for i in range(len(rooms)): for j in range(len(rooms[0])): if rooms[i][j] == 0: _dfs(rooms, i, j, 0) def _dfs(rooms: list[list[int]], i: int, j: int, depth: int) -> None: """Recursive DFS from a gate, updating room distances. Args: rooms: The grid (modified in place). i: Row index. j: Column index. depth: Current distance from the gate. """ if i < 0 or i >= len(rooms) or j < 0 or j >= len(rooms[0]): return if rooms[i][j] < depth: return rooms[i][j] = depth _dfs(rooms, i + 1, j, depth + 1) _dfs(rooms, i - 1, j, depth + 1) _dfs(rooms, i, j + 1, depth + 1) _dfs(rooms, i, j - 1, depth + 1)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/walls_and_gates.py", "license": "MIT License", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/graph/word_ladder.py
""" Word Ladder (Bidirectional BFS) Given two words and a dictionary, find the length of the shortest transformation sequence where only one letter changes at each step and every intermediate word must exist in the dictionary. Reference: https://leetcode.com/problems/word-ladder/ Complexity: Time: O(N * L^2) where N = size of word list, L = word length Space: O(N * L) """ from __future__ import annotations from collections.abc import Iterator def ladder_length(begin_word: str, end_word: str, word_list: list[str]) -> int: """Return the shortest transformation length, or -1 if impossible. Args: begin_word: Starting word. end_word: Target word. word_list: Allowed intermediate words. Returns: Length of the shortest transformation sequence, or -1. Examples: >>> ladder_length('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log']) 5 """ if len(begin_word) != len(end_word): return -1 if begin_word == end_word: return 0 if sum(c1 != c2 for c1, c2 in zip(begin_word, end_word, strict=False)) == 1: return 1 begin_set: set[str] = set() end_set: set[str] = set() begin_set.add(begin_word) end_set.add(end_word) result = 2 while begin_set and end_set: if len(begin_set) > len(end_set): begin_set, end_set = end_set, begin_set next_begin_set: set[str] = set() for word in begin_set: for ladder_word in _word_range(word): if ladder_word in end_set: return result if ladder_word in word_list: next_begin_set.add(ladder_word) word_list.remove(ladder_word) begin_set = next_begin_set result += 1 return -1 def _word_range(word: str) -> Iterator[str]: """Yield all words that differ from *word* by exactly one letter. Args: word: The source word. Yields: Words with a single character changed. """ for ind in range(len(word)): temp = word[ind] for c in [chr(x) for x in range(ord("a"), ord("z") + 1)]: if c != temp: yield word[:ind] + c + word[ind + 1 :]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/graph/word_ladder.py", "license": "MIT License", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/add_two_numbers.py
""" Add Two Numbers (Linked List) Given two non-empty linked lists representing two non-negative integers with digits stored in reverse order, add the two numbers and return the sum as a linked list. Reference: https://leetcode.com/problems/add-two-numbers/ Complexity: Time: O(max(m, n)) Space: O(max(m, n)) """ from __future__ import annotations class Node: def __init__(self, x: int) -> None: self.val = x self.next: Node | None = None def add_two_numbers(left: Node, right: Node) -> Node: """Add two numbers represented as reversed linked lists. Args: left: Head of the first number's linked list. right: Head of the second number's linked list. Returns: Head of the resulting sum linked list. Examples: >>> # (2 -> 4 -> 3) + (5 -> 6 -> 4) = (7 -> 0 -> 8) >>> l1 = Node(2); l1.next = Node(4); l1.next.next = Node(3) >>> l2 = Node(5); l2.next = Node(6); l2.next.next = Node(4) >>> convert_to_str(add_two_numbers(l1, l2)) '708' """ head = Node(0) current = head carry = 0 while left or right: carry //= 10 if left: carry += left.val left = left.next if right: carry += right.val right = right.next current.next = Node(carry % 10) current = current.next if carry // 10 == 1: current.next = Node(1) return head.next def convert_to_list(number: int) -> Node | None: """Convert a non-negative integer into a reversed linked list. Args: number: A non-negative integer to convert. Returns: Head of the reversed linked list, or None if number is negative. Examples: >>> convert_to_str(convert_to_list(112)) '211' """ if number < 0: return None head = Node(0) current = head remainder = number % 10 quotient = number // 10 while quotient != 0: current.next = Node(remainder) current = current.next remainder = quotient % 10 quotient //= 10 current.next = Node(remainder) return head.next def convert_to_str(node: Node | None) -> str: """Convert a linked list of digits to a string. Args: node: Head of the linked list. Returns: String representation of the linked list values. Examples: >>> n = Node(2); n.next = Node(4); n.next.next = Node(3) >>> convert_to_str(n) '243' """ result = "" while node: result += str(node.val) node = node.next return result
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/add_two_numbers.py", "license": "MIT License", "lines": 84, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/copy_random_pointer.py
""" Copy List with Random Pointer Given a linked list where each node contains an additional random pointer that could point to any node in the list or null, return a deep copy of the list. Reference: https://leetcode.com/problems/copy-list-with-random-pointer/ Complexity: Time: O(n) Space: O(n) """ from __future__ import annotations from collections import defaultdict class RandomListNode: """Node with next and random pointers for deep-copy problem.""" def __init__(self, label: int) -> None: self.label = label self.next: RandomListNode | None = None self.random: RandomListNode | None = None def copy_random_pointer_v1(head: RandomListNode | None) -> RandomListNode | None: """Deep-copy a linked list with random pointers using a dictionary. Args: head: Head of the original list. Returns: Head of the deep-copied list. Examples: >>> node = RandomListNode(1) >>> node.random = node >>> copied = copy_random_pointer_v1(node) >>> copied.label == 1 and copied.random is copied True """ node_map: dict[RandomListNode, RandomListNode] = {} current = head while current: node_map[current] = RandomListNode(current.label) current = current.next current = head while current: node_map[current].next = node_map.get(current.next) node_map[current].random = node_map.get(current.random) current = current.next return node_map.get(head) def copy_random_pointer_v2(head: RandomListNode | None) -> RandomListNode | None: """Deep-copy a linked list with random pointers using defaultdict. Args: head: Head of the original list. Returns: Head of the deep-copied list. Examples: >>> node = RandomListNode(1) >>> node.random = node >>> copied = copy_random_pointer_v2(node) >>> copied.label == 1 and copied.random is copied True """ copy: defaultdict[RandomListNode | None, RandomListNode | None] = defaultdict( lambda: RandomListNode(0) ) copy[None] = None node = head while node: copy[node].label = node.label copy[node].next = copy[node.next] copy[node].random = copy[node.random] node = node.next return copy[head]
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/copy_random_pointer.py", "license": "MIT License", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/delete_node.py
""" Delete Node in a Linked List Given only access to a node (not the tail) in a singly linked list, delete that node by copying the next node's value and skipping over it. Reference: https://leetcode.com/problems/delete-node-in-a-linked-list/ Complexity: Time: O(1) Space: O(1) """ from __future__ import annotations class Node: def __init__(self, x: int) -> None: self.val = x self.next: Node | None = None def delete_node(node: Node | None) -> None: """Delete the given node from a singly linked list in-place. The node must not be the tail node. The deletion is performed by copying the value from the next node and then skipping the next node. Args: node: The node to delete (must not be None or the tail). Raises: ValueError: If node is None or is the tail node. Examples: >>> head = Node(1); head.next = Node(2); head.next.next = Node(3) >>> delete_node(head.next) >>> head.next.val 3 """ if node is None or node.next is None: raise ValueError node.val = node.next.val node.next = node.next.next
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/delete_node.py", "license": "MIT License", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/first_cyclic_node.py
""" First Cyclic Node Given a linked list, find the first node of a cycle in it using Floyd's cycle-finding algorithm (Tortoise and Hare). Reference: https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare Complexity: Time: O(n) Space: O(1) """ from __future__ import annotations class Node: def __init__(self, x: object) -> None: self.val = x self.next: Node | None = None def first_cyclic_node(head: Node | None) -> Node | None: """Find the first node of a cycle in the linked list. Args: head: Head of the linked list. Returns: The first node in the cycle, or None if there is no cycle. Examples: >>> a = Node(1); b = Node(2); c = Node(3) >>> a.next = b; b.next = c; c.next = b >>> first_cyclic_node(a).val 2 """ runner = walker = head while runner and runner.next: runner = runner.next.next walker = walker.next if runner is walker: break if runner is None or runner.next is None: return None walker = head while runner is not walker: runner, walker = runner.next, walker.next return runner
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/first_cyclic_node.py", "license": "MIT License", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/intersection.py
""" 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: Time: O(m + n) Space: O(1) """ 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: """Find the intersection node of two linked lists. Args: h1: Head of the first linked list. h2: Head of the second linked list. Returns: The intersecting node, or None if the lists do not intersect. Examples: >>> shared = Node(7) >>> a = Node(1); a.next = shared >>> b = Node(2); b.next = shared >>> intersection(a, b).val 7 """ count = 0 flag = None h1_orig = h1 h2_orig = h2 while h1 or h2: count += 1 if not flag and (h1.next is None or h2.next is None): flag = (count, h1.next, h2.next) if h1: h1 = h1.next if h2: h2 = h2.next long_len = count short_len = flag[0] if flag[1] is None: shorter = h1_orig longer = h2_orig elif flag[2] is None: shorter = h2_orig longer = h1_orig while longer and shorter: while long_len > short_len: longer = longer.next long_len -= 1 if longer == shorter: return longer else: longer = longer.next shorter = shorter.next return None
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/intersection.py", "license": "MIT License", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
keon/algorithms:algorithms/linked_list/is_cyclic.py
""" 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 annotations class Node: def __init__(self, x: object) -> None: self.val = x self.next: Node | None = None def is_cyclic(head: Node | None) -> bool: """Determine whether a linked list contains a cycle. Args: head: Head of the linked list. Returns: True if the list has a cycle, False otherwise. Examples: >>> a = Node(1); b = Node(2); a.next = b; b.next = a >>> is_cyclic(a) True >>> c = Node(3); c.next = Node(4) >>> is_cyclic(c) False """ if not head: return False runner = head walker = head while runner.next and runner.next.next: runner = runner.next.next walker = walker.next if runner == walker: return True return False
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/is_cyclic.py", "license": "MIT License", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/is_palindrome.py
""" 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: O(1) """ from __future__ import annotations def is_palindrome(head: object | None) -> bool: """Check if a linked list is a palindrome by reversing the second half. Args: head: Head node of the linked list (must have .val and .next attrs). Returns: True if the list is a palindrome, False otherwise. Examples: >>> is_palindrome(None) True """ 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: nxt = second.next second.next = node node = second second = nxt while node: if node.val != head.val: return False node = node.next head = head.next return True def is_palindrome_stack(head: object | None) -> bool: """Check if a linked list is a palindrome using a stack. Args: head: Head node of the linked list. Returns: True if the list is a palindrome, False otherwise. Examples: >>> is_palindrome_stack(None) True """ if not head or not head.next: return True slow = fast = current = head while fast and fast.next: fast, slow = fast.next.next, slow.next stack = [slow.val] while slow.next: slow = slow.next stack.append(slow.val) while stack: if stack.pop() != current.val: return False current = current.next return True def is_palindrome_dict(head: object | None) -> bool: """Check if a linked list is a palindrome using a dictionary of positions. Builds a dictionary mapping each value to its list of positions, then verifies that positions are symmetric around the center. Args: head: Head node of the linked list. Returns: True if the list is a palindrome, False otherwise. Examples: >>> is_palindrome_dict(None) True """ if not head or not head.next: return True positions: dict[object, list[int]] = {} pos = 0 current = head while current: if current.val in positions: positions[current.val].append(pos) else: positions[current.val] = [pos] current = current.next pos += 1 checksum = pos - 1 middle = 0 for indices in positions.values(): if len(indices) % 2 != 0: middle += 1 else: for step, i in enumerate(range(len(indices))): if indices[i] + indices[len(indices) - 1 - step] != checksum: return False if middle > 1: return False return True
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/is_palindrome.py", "license": "MIT License", "lines": 100, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
keon/algorithms:algorithms/linked_list/is_sorted.py
""" 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 annotations def is_sorted(head: object | None) -> bool: """Check if a linked list is sorted in non-decreasing order. Args: head: Head node of the linked list (must have .val and .next attrs). Returns: True if the list is sorted or empty, False otherwise. Examples: >>> is_sorted(None) True """ if not head: return True current = head while current.next: if current.val > current.next.val: return False current = current.next return True
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/is_sorted.py", "license": "MIT License", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/kth_to_last.py
""" Kth to Last Element Find the kth to last element of a singly linked list. Three approaches are provided: eval-based, dictionary-based, and two-pointer iterative. Reference: https://en.wikipedia.org/wiki/Linked_list Complexity (two-pointer): Time: O(n) Space: O(1) """ from __future__ import annotations class Node: def __init__(self, val: object = None) -> None: self.val = val self.next: Node | None = None def kth_to_last_eval(head: Node, k: int) -> Node | bool: """Find the kth to last element using eval (not safe for user input). Args: head: Head of the linked list. k: Position from the end (1-indexed). Returns: The kth to last node, or False if k is invalid. Examples: >>> a = Node(1); b = Node(2); a.next = b >>> kth_to_last_eval(a, 1).val 2 """ if not isinstance(k, int) or not head.val: return False nexts = ".".join(["next" for _ in range(1, k + 1)]) seeker = ".".join(["head", nexts]) while head: if eval(seeker) is None: # noqa: S307 return head else: head = head.next return False def kth_to_last_dict(head: Node | None, k: int) -> Node | bool: """Find the kth to last element using a dictionary. Args: head: Head of the linked list. k: Position from the end (1-indexed). Returns: The kth to last node, or False if k is invalid. Examples: >>> a = Node(1); b = Node(2); a.next = b >>> kth_to_last_dict(a, 1).val 2 """ if not (head and k > -1): return False index_map: dict[int, Node] = {} count = 0 while head: index_map[count] = head head = head.next count += 1 return len(index_map) - k in index_map and index_map[len(index_map) - k] def kth_to_last(head: Node | None, k: int) -> Node | bool: """Find the kth to last element using two pointers. Advances the first pointer k steps ahead, then moves both pointers together until the first pointer reaches the end. Args: head: Head of the linked list. k: Position from the end (1-indexed). Returns: The kth to last node, or False if the list is empty. Raises: IndexError: If k exceeds the length of the list. Examples: >>> a = Node(1); b = Node(2); a.next = b >>> kth_to_last(a, 1).val 2 """ if not (head or k > -1): return False ahead = head behind = head for _ in range(1, k + 1): if ahead is None: raise IndexError ahead = ahead.next while ahead: ahead = ahead.next behind = behind.next return behind
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/kth_to_last.py", "license": "MIT License", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/merge_two_list.py
""" Merge Two Sorted Lists Merge two sorted linked lists into a single sorted list by splicing together the nodes of the two input lists. Reference: https://leetcode.com/problems/merge-two-sorted-lists/ Complexity: Time: O(m + n) Space: O(1) iterative, O(m + n) recursive """ from __future__ import annotations class Node: def __init__(self, x: int) -> None: self.val = x self.next: Node | None = None def merge_two_list(l1: Node | None, l2: Node | None) -> Node | None: """Merge two sorted linked lists iteratively. Args: l1: Head of the first sorted list. l2: Head of the second sorted list. Returns: Head of the merged sorted list. Examples: >>> a = Node(1); a.next = Node(3) >>> b = Node(2); b.next = Node(4) >>> result = merge_two_list(a, b) >>> result.val 1 """ sentinel = current = Node(0) while l1 and l2: if l1.val < l2.val: current.next = l1 l1 = l1.next else: current.next = l2 l2 = l2.next current = current.next current.next = l1 or l2 return sentinel.next def merge_two_list_recur(l1: Node | None, l2: Node | None) -> Node | None: """Merge two sorted linked lists recursively. Args: l1: Head of the first sorted list. l2: Head of the second sorted list. Returns: Head of the merged sorted list. Examples: >>> a = Node(1); a.next = Node(3) >>> b = Node(2); b.next = Node(4) >>> result = merge_two_list_recur(a, b) >>> result.val 1 """ if not l1 or not l2: return l1 or l2 if l1.val < l2.val: l1.next = merge_two_list_recur(l1.next, l2) return l1 else: l2.next = merge_two_list_recur(l1, l2.next) return l2
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/merge_two_list.py", "license": "MIT License", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/partition.py
""" 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 __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: """Partition a linked list in-place around value x. Rearranges nodes so that all nodes with values less than x appear before nodes with values greater than or equal to x. Args: head: Head of the linked list. x: The partition value. Returns: None. The list is modified in-place. Examples: >>> a = Node(3); b = Node(5); c = Node(1) >>> a.next = b; b.next = c >>> partition(a, 5) """ left = None right = None prev = None current = head while current: if int(current.val) >= x: if not right: right = current else: if not left: left = current else: prev.next = current.next left.next = current left = current left.next = right if prev and prev.next is None: break prev = current current = current.next
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/partition.py", "license": "MIT License", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/remove_duplicates.py
""" 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): Time: O(n) Space: O(n) """ 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: """Remove duplicates from an unsorted linked list using a hash set. Args: head: Head of the linked list. Modified in-place. Returns: None. The list is modified in-place. Examples: >>> a = Node(1); b = Node(2); c = Node(1) >>> a.next = b; b.next = c >>> remove_dups(a) >>> a.next.val 2 """ seen: set[object] = set() prev = Node() while head: if head.val in seen: prev.next = head.next else: seen.add(head.val) prev = head head = head.next def remove_dups_wothout_set(head: Node | None) -> None: """Remove duplicates from an unsorted linked list without extra space. Uses a runner pointer to check for duplicates of each node value. Args: head: Head of the linked list. Modified in-place. Returns: None. The list is modified in-place. Examples: >>> a = Node(1); b = Node(2); c = Node(1) >>> a.next = b; b.next = c >>> remove_dups_wothout_set(a) >>> a.next.val 2 """ current = head while current: runner = current while runner.next: if runner.next.val == current.val: runner.next = runner.next.next else: runner = runner.next current = current.next
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/remove_duplicates.py", "license": "MIT License", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/remove_range.py
""" 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 annotations def remove_range(head: object | None, start: int, end: int) -> object | None: """Remove nodes from index start to end (inclusive) from a linked list. Args: head: Head node of the linked list (must have .next attr). start: Starting index of the range to remove. end: Ending index of the range to remove (inclusive). Returns: The (possibly new) head of the modified list. Examples: >>> remove_range(None, 0, 0) is None True """ 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): current = current.next for _ in range(end - start + 1): if current is not None and current.next is not None: current.next = current.next.next return head
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/remove_range.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/reverse.py
""" Reverse Linked List Reverse a singly linked list. Both iterative and recursive solutions are provided. Reference: https://leetcode.com/problems/reverse-linked-list/ Complexity: Time: O(n) Space: O(1) iterative, O(n) recursive """ from __future__ import annotations def reverse_list(head: object | None) -> object | None: """Reverse a singly linked list iteratively. Args: head: Head node of the linked list (must have .next attr). Returns: The new head of the reversed list. Examples: >>> reverse_list(None) is None True """ if not head or not head.next: return head prev = None while head: current = head head = head.next current.next = prev prev = current return prev def reverse_list_recursive(head: object | None) -> object | None: """Reverse a singly linked list recursively. Args: head: Head node of the linked list (must have .next attr). Returns: The new head of the reversed list. Examples: >>> reverse_list_recursive(None) is None True """ if head is None or head.next is None: return head rest = head.next head.next = None reversed_rest = reverse_list_recursive(rest) rest.next = head return reversed_rest
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/reverse.py", "license": "MIT License", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/rotate_list.py
""" 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 | None, k: int) -> object | None: """Rotate a linked list to the right by k positions. Args: head: Head node of the linked list (must have .val and .next attrs). k: Number of positions to rotate right (non-negative). Returns: The new head of the rotated list. Examples: >>> rotate_right(None, 5) is None True """ 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 range(length - k): current = current.next head = current.next current.next = None return head
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/rotate_list.py", "license": "MIT License", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/linked_list/swap_in_pairs.py
""" 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 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: """Swap every two adjacent nodes in a linked list. Args: head: Head of the linked list. Returns: The new head after pairwise swapping. Examples: >>> a = Node(1); b = Node(2); a.next = b >>> result = swap_pairs(a) >>> result.val 2 """ if not head: return head sentinel = Node(0) sentinel.next = head current = sentinel while current.next and current.next.next: first = current.next second = current.next.next first.next = second.next current.next = second current.next.next = first current = current.next.next return sentinel.next
{ "repo_id": "keon/algorithms", "file_path": "algorithms/linked_list/swap_in_pairs.py", "license": "MIT License", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/base_conversion.py
""" 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 directions Space: O(log_base(num)) """ from __future__ import annotations import string def int_to_base(num: int, base: int) -> str: """Convert a base-10 integer to a string in the given base. Args: num: The integer to convert. base: The target base (2-36). Returns: String representation of num in the given base. Examples: >>> int_to_base(5, 2) '101' >>> int_to_base(255, 16) 'FF' >>> int_to_base(0, 2) '0' """ 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 += digit[num % base] num //= base if is_negative: return "-" + res[::-1] return res[::-1] def base_to_int(str_to_convert: str, base: int) -> int: """Convert a string in a given base to a base-10 integer. Args: str_to_convert: The string representation of the number. base: The base of the input string (2-36). Returns: The base-10 integer value. Examples: >>> base_to_int('101', 2) 5 >>> base_to_int('FF', 16) 255 """ digit = {} for ind, char in enumerate(string.digits + string.ascii_uppercase): digit[char] = ind multiplier = 1 res = 0 for char in str_to_convert[::-1]: res += digit[char] * multiplier multiplier *= base return res
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/base_conversion.py", "license": "MIT License", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/chinese_remainder_theorem.py
""" Chinese Remainder Theorem Solves a system of simultaneous congruences using the Chinese Remainder Theorem. Given pairwise coprime moduli, finds the smallest positive integer satisfying all congruences. Reference: https://en.wikipedia.org/wiki/Chinese_remainder_theorem Complexity: Time: O(n * m) where n is the number of equations and m is the solution Space: O(1) """ from __future__ import annotations from algorithms.math.gcd import gcd def solve_chinese_remainder(nums: list[int], rems: list[int]) -> int: """Find the smallest x satisfying x % nums[i] == rems[i] for all i. Args: nums: List of pairwise coprime moduli, each greater than 1. rems: List of remainders corresponding to each modulus. Returns: The smallest positive integer satisfying all congruences. Raises: Exception: If inputs are invalid or moduli are not pairwise coprime. Examples: >>> solve_chinese_remainder([3, 7, 10], [2, 3, 3]) 143 """ if not len(nums) == len(rems): raise Exception("nums and rems should have equal length") if not len(nums) > 0: raise Exception("Lists nums and rems need to contain at least one element") for num in nums: if not num > 1: raise Exception("All numbers in nums needs to be > 1") if not _check_coprime(nums): raise Exception("All pairs of numbers in nums are not coprime") k = len(nums) x = 1 while True: i = 0 while i < k: if x % nums[i] != rems[i]: break i += 1 if i == k: return x x += 1 def _check_coprime(list_to_check: list[int]) -> bool: """Check whether all pairs of numbers in the list are coprime. Args: list_to_check: List of integers to check for pairwise coprimality. Returns: True if all pairs are coprime, False otherwise. """ for ind, num in enumerate(list_to_check): for num2 in list_to_check[ind + 1 :]: if gcd(num, num2) != 1: return False return True
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/chinese_remainder_theorem.py", "license": "MIT License", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/combination.py
""" 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) recursive stack, O(n*r) memoized """ from __future__ import annotations def combination(n: int, r: int) -> int: """Calculate nCr using naive recursion. Args: n: Total number of items. r: Number of items to choose. Returns: The number of combinations. Examples: >>> combination(5, 2) 10 >>> combination(10, 5) 252 """ 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: """Calculate nCr using memoization. Args: n: Total number of items. r: Number of items to choose. Returns: The number of combinations. Examples: >>> combination_memo(50, 10) 10272278170 """ memo: dict[tuple[int, int], int] = {} def _recur(n: int, r: int) -> int: if n == r or r == 0: return 1 if (n, r) not in memo: memo[(n, r)] = _recur(n - 1, r - 1) + _recur(n - 1, r) return memo[(n, r)] return _recur(n, r)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/combination.py", "license": "MIT License", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/cosine_similarity.py
""" 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) Space: O(1) """ from __future__ import annotations import math def _l2_distance(vec: list[float]) -> float: """Calculate the L2 (Euclidean) norm of a vector. Args: vec: Input vector as a list of numbers. Returns: The L2 norm of the vector. """ 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: """Calculate cosine similarity between two vectors. Args: vec1: First vector. vec2: Second vector (must be same length as vec1). Returns: Cosine similarity value between -1 and 1. Raises: ValueError: If vectors have different lengths. Examples: >>> cosine_similarity([1, 1, 1], [1, 2, -1]) 0.4714045207910317 """ if len(vec1) != len(vec2): raise ValueError( "The two vectors must be the same length. Got shape " + str(len(vec1)) + " and " + str(len(vec2)) ) norm_a = _l2_distance(vec1) norm_b = _l2_distance(vec2) similarity = 0.0 for vec1_element, vec2_element in zip(vec1, vec2, strict=False): similarity += vec1_element * vec2_element similarity /= norm_a * norm_b return similarity
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/cosine_similarity.py", "license": "MIT License", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/decimal_to_binary_ip.py
""" 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 annotations def decimal_to_binary_util(val: str) -> str: """Convert a single decimal octet (0-255) to an 8-bit binary string. Args: val: String representation of an octet value. Returns: 8-character binary string. Examples: >>> decimal_to_binary_util('192') '11000000' """ 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) return binary_rep def decimal_to_binary_ip(ip: str) -> str: """Convert a dotted-decimal IP address to binary representation. Args: ip: IP address in dotted-decimal format (e.g., '192.168.0.1'). Returns: Binary representation with dot-separated octets. Examples: >>> decimal_to_binary_ip('192.168.0.1') '11000000.10101000.00000000.00000001' """ values = ip.split(".") binary_list = [] for val in values: binary_list.append(decimal_to_binary_util(val)) return ".".join(binary_list)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/decimal_to_binary_ip.py", "license": "MIT License", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/diffie_hellman_key_exchange.py
""" 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 Complexity: Time: O(p) for primitive root finding, O(log(p)) for key generation Space: O(p) for primitive root list """ from __future__ import annotations import math from random import randint def _prime_check(num: int) -> bool: """Check whether a number is prime. Args: num: The integer to test. Returns: True if num is prime, False otherwise. """ 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) == 0: return False j += 6 return True def _find_order(a: int, n: int) -> int: """Find the multiplicative order of a modulo n. Args: a: The base integer. n: The modulus. Returns: The smallest positive k such that a^k = 1 (mod n), or -1 if none exists. """ 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: """Compute Euler's totient function phi(n). Args: n: A positive integer. Returns: The number of integers from 1 to n that are coprime with n. """ 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 def _find_primitive_root(n: int) -> list[int]: """Find all primitive roots of n. Args: n: A positive integer. Returns: List of all primitive roots of n, or empty list if none exist. """ if n == 1: return [0] phi = _euler_totient(n) p_root_list = [] for i in range(1, n): if math.gcd(i, n) != 1: continue order = _find_order(i, n) if order == phi: p_root_list.append(i) return p_root_list def alice_private_key(p: int) -> int: """Generate Alice's private key in range [1, p-1]. Args: p: A large prime number. Returns: A random private key. """ return randint(1, p - 1) def alice_public_key(a_pr_k: int, a: int, p: int) -> int: """Calculate Alice's public key. Args: a_pr_k: Alice's private key. a: The primitive root (generator). p: The prime modulus. Returns: Alice's public key. """ return pow(a, a_pr_k) % p def bob_private_key(p: int) -> int: """Generate Bob's private key in range [1, p-1]. Args: p: A large prime number. Returns: A random private key. """ return randint(1, p - 1) def bob_public_key(b_pr_k: int, a: int, p: int) -> int: """Calculate Bob's public key. Args: b_pr_k: Bob's private key. a: The primitive root (generator). p: The prime modulus. Returns: Bob's public key. """ return pow(a, b_pr_k) % p def alice_shared_key(b_pu_k: int, a_pr_k: int, p: int) -> int: """Calculate Alice's shared secret key. Args: b_pu_k: Bob's public key. a_pr_k: Alice's private key. p: The prime modulus. Returns: The shared secret key. """ return pow(b_pu_k, a_pr_k) % p def bob_shared_key(a_pu_k: int, b_pr_k: int, p: int) -> int: """Calculate Bob's shared secret key. Args: a_pu_k: Alice's public key. b_pr_k: Bob's private key. p: The prime modulus. Returns: The shared secret key. """ return pow(a_pu_k, b_pr_k) % p def diffie_hellman_key_exchange(a: int, p: int, option: int | None = None) -> bool: """Perform Diffie-Hellman key exchange and verify shared keys match. Args: a: The primitive root (generator). p: A large prime number. option: Unused, kept for API compatibility. Returns: True if both parties compute the same shared key, False if inputs are invalid. Examples: >>> diffie_hellman_key_exchange(3, 353) True """ if _prime_check(p) is False: return False try: p_root_list = _find_primitive_root(p) p_root_list.index(a) except ValueError: return False a_pr_k = alice_private_key(p) a_pu_k = alice_public_key(a_pr_k, a, p) b_pr_k = bob_private_key(p) b_pu_k = bob_public_key(b_pr_k, a, p) a_sh_k = alice_shared_key(b_pu_k, a_pr_k, p) b_sh_k = bob_shared_key(a_pu_k, b_pr_k, p) return a_sh_k == b_sh_k
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/diffie_hellman_key_exchange.py", "license": "MIT License", "lines": 165, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/distance_between_two_points.py
""" 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 __future__ import annotations from math import sqrt def distance_between_two_points(x1: float, y1: float, x2: float, y2: float) -> float: """Calculate the Euclidean distance between two points in 2D space. Args: x1: x-coordinate of the first point. y1: y-coordinate of the first point. x2: x-coordinate of the second point. y2: y-coordinate of the second point. Returns: The Euclidean distance between the two points. Examples: >>> distance_between_two_points(0, 0, 3, 4) 5.0 >>> distance_between_two_points(-1, -1, 2, 3) 5.0 """ return sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/distance_between_two_points.py", "license": "MIT License", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/euler_totient.py
""" 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 __future__ import annotations def euler_totient(n: int) -> int: """Compute Euler's totient function phi(n). Args: n: A positive integer. Returns: The count of integers in [1, n] coprime to n. Examples: >>> euler_totient(8) 4 >>> euler_totient(21) 12 """ 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
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/euler_totient.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/extended_gcd.py
""" 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 __future__ import annotations def extended_gcd(num1: int, num2: int) -> tuple[int, int, int]: """Compute the extended GCD of two integers. Args: num1: First integer. num2: Second integer. Returns: A tuple (s, t, g) where num1 * s + num2 * t = g = gcd(num1, num2). Examples: >>> extended_gcd(8, 2) (0, 1, 2) >>> extended_gcd(13, 17) (0, 1, 17) """ 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 = t, old_t - quotient * t return old_s, old_t, old_r
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/extended_gcd.py", "license": "MIT License", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/factorial.py
""" 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 factorial(n: int, mod: int | None = None) -> int: """Calculate n! iteratively, optionally modulo mod. Args: n: A non-negative integer. mod: Optional positive integer modulus. Returns: n! or n! % mod if mod is provided. Raises: ValueError: If n is negative or mod is not a positive integer. Examples: >>> factorial(5) 120 >>> factorial(10) 3628800 """ 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 integer") result = 1 if n == 0: return 1 for i in range(2, n + 1): result *= i if mod: result %= mod return result def factorial_recur(n: int, mod: int | None = None) -> int: """Calculate n! recursively, optionally modulo mod. Args: n: A non-negative integer. mod: Optional positive integer modulus. Returns: n! or n! % mod if mod is provided. Raises: ValueError: If n is negative or mod is not a positive integer. Examples: >>> factorial_recur(5) 120 """ 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 integer") if n == 0: return 1 result = n * factorial(n - 1, mod) if mod: result %= mod return result
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/factorial.py", "license": "MIT License", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/fft.py
""" 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: Time: O(n log n) Space: O(n log n) """ from __future__ import annotations from cmath import exp, pi def fft(x: list[complex]) -> list[complex]: """Compute the FFT of a sequence using the Cooley-Tukey algorithm. Args: x: Input array of complex values. Length must be a power of 2. Returns: The Discrete Fourier Transform of x. Examples: >>> fft([1.0, 1.0, 1.0, 1.0]) [(4+0j), 0j, 0j, 0j] """ 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] = even[k] + q y[k + n // 2] = even[k] - q return y
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/fft.py", "license": "MIT License", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/find_order_simple.py
""" 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) """ from __future__ import annotations import math def find_order(a: int, n: int) -> int: """Find the multiplicative order of a modulo n. Args: a: The base integer. n: The modulus. Returns: The smallest positive k where a^k = 1 (mod n), or -1 if a and n are not coprime. Examples: >>> find_order(3, 7) 6 >>> find_order(1, 1) 1 """ 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
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/find_order_simple.py", "license": "MIT License", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/find_primitive_root_simple.py
""" 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) Space: O(n) """ from __future__ import annotations import math def _find_order(a: int, n: int) -> int: """Find the multiplicative order of a modulo n. Args: a: The base integer. n: The modulus. Returns: The smallest positive k where a^k = 1 (mod n), or -1 if none exists. """ 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: """Compute Euler's totient function phi(n). Args: n: A positive integer. Returns: The count of integers in [1, n] coprime to n. """ 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 def find_primitive_root(n: int) -> list[int]: """Find all primitive roots of n. Args: n: A positive integer. Returns: List of all primitive roots of n. Returns [0] for n=1, or an empty list if no primitive roots exist. Examples: >>> find_primitive_root(5) [2, 3] >>> find_primitive_root(1) [0] """ if n == 1: return [0] phi = _euler_totient(n) p_root_list = [] for i in range(1, n): if math.gcd(i, n) == 1: order = _find_order(i, n) if order == phi: p_root_list.append(i) return p_root_list
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/find_primitive_root_simple.py", "license": "MIT License", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/gcd.py
""" 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 Space: O(1) """ from __future__ import annotations def gcd(a: int, b: int) -> int: """Compute the greatest common divisor using Euclid's algorithm. Args: a: First integer (non-zero). b: Second integer (non-zero). Returns: The greatest common divisor of a and b. Raises: ValueError: If inputs are not integers or either is zero. Examples: >>> gcd(8, 12) 4 >>> gcd(13, 17) 1 """ 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 input arguments equals zero") while b != 0: a, b = b, a % b return a def lcm(a: int, b: int) -> int: """Compute the lowest common multiple of two integers. Args: a: First integer (non-zero). b: Second integer (non-zero). Returns: The lowest common multiple of a and b. Examples: >>> lcm(8, 12) 24 """ return abs(a) * abs(b) / gcd(a, b) def trailing_zero(x: int) -> int: """Count the number of trailing zeros in the binary representation. Args: x: A positive integer. Returns: Number of trailing zero bits. Examples: >>> trailing_zero(34) 1 >>> trailing_zero(40) 3 """ count = 0 while x and not x & 1: count += 1 x >>= 1 return count def gcd_bit(a: int, b: int) -> int: """Compute GCD using the binary (Stein's) algorithm. Args: a: First non-negative integer. b: Second non-negative integer. Returns: The greatest common divisor of a and b. Examples: >>> gcd_bit(8, 12) 4 """ tza = trailing_zero(a) tzb = trailing_zero(b) a >>= tza b >>= tzb while b: if a < b: a, b = b, a a -= b a >>= trailing_zero(a) return a << min(tza, tzb)
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/gcd.py", "license": "MIT License", "lines": 86, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/generate_strobogrammtic.py
""" 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/2)) for generation Space: O(5^(n/2)) """ from __future__ import annotations def gen_strobogrammatic(n: int) -> list[str]: """Generate all strobogrammatic numbers of length n. Args: n: The desired length of strobogrammatic numbers. Returns: List of strobogrammatic number strings. Examples: >>> gen_strobogrammatic(2) ['88', '11', '96', '69'] """ return _helper(n, n) def _helper(n: int, length: int) -> list[str]: """Recursively build strobogrammatic numbers of length n. Args: n: Remaining length to fill. length: Original target length. Returns: List of strobogrammatic number strings. """ if n == 0: return [""] if n == 1: return ["1", "0", "8"] middles = _helper(n - 2, length) result = [] for middle in middles: if n != length: result.append("0" + middle + "0") result.append("8" + middle + "8") result.append("1" + middle + "1") result.append("9" + middle + "6") result.append("6" + middle + "9") return result def strobogrammatic_in_range(low: str, high: str) -> int: """Count strobogrammatic numbers within the given range [low, high]. Args: low: Lower bound as a string. high: Upper bound as a string. Returns: Count of strobogrammatic numbers in the range. Examples: >>> strobogrammatic_in_range("10", "100") 4 """ res: list[str] = [] count = 0 low_len = len(low) high_len = len(high) for i in range(low_len, high_len + 1): res.extend(_helper2(i, i)) for perm in res: if len(perm) == low_len and int(perm) < int(low): continue if len(perm) == high_len and int(perm) > int(high): continue count += 1 return count def _helper2(n: int, length: int) -> list[str]: """Recursively build strobogrammatic numbers including leading zeros. Args: n: Remaining length to fill. length: Original target length. Returns: List of strobogrammatic number strings. """ if n == 0: return [""] if n == 1: return ["0", "8", "1"] mids = _helper(n - 2, length) res = [] for mid in mids: if n != length: res.append("0" + mid + "0") res.append("1" + mid + "1") res.append("6" + mid + "9") res.append("9" + mid + "6") res.append("8" + mid + "8") return res
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/generate_strobogrammtic.py", "license": "MIT License", "lines": 89, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/hailstone.py
""" 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) - conjectured to always terminate Space: O(sequence length) """ from __future__ import annotations def hailstone(n: int) -> list[int]: """Generate the hailstone sequence from n to 1. Args: n: The starting positive integer. Returns: The complete hailstone sequence from n down to 1. Examples: >>> hailstone(8) [8, 4, 2, 1] >>> hailstone(10) [10, 5, 16, 8, 4, 2, 1] """ sequence = [n] while n > 1: n = 3 * n + 1 if n % 2 != 0 else int(n / 2) sequence.append(n) return sequence
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/hailstone.py", "license": "MIT License", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/is_strobogrammatic.py
""" 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 Space: O(1) for is_strobogrammatic, O(n) for is_strobogrammatic2 """ from __future__ import annotations def is_strobogrammatic(num: str) -> bool: """Check if a number string is strobogrammatic using two pointers. Args: num: String representation of the number. Returns: True if num is strobogrammatic, False otherwise. Examples: >>> is_strobogrammatic("69") True >>> is_strobogrammatic("14") False """ 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: """Check if a number string is strobogrammatic using string reversal. Args: num: String representation of the number. Returns: True if num is strobogrammatic, False otherwise. Examples: >>> is_strobogrammatic2("69") True >>> is_strobogrammatic2("14") False """ return num == num[::-1].replace("6", "#").replace("9", "6").replace("#", "9")
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/is_strobogrammatic.py", "license": "MIT License", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/krishnamurthy_number.py
""" 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 digit value Space: O(1) """ from __future__ import annotations def _find_factorial(n: int) -> int: """Calculate the factorial of a non-negative integer. Args: n: A non-negative integer. Returns: The factorial of n. """ fact = 1 while n != 0: fact *= n n -= 1 return fact def krishnamurthy_number(n: int) -> bool: """Check if n is a Krishnamurthy number (factorion). Args: n: The integer to check. Returns: True if n is a Krishnamurthy number, False otherwise. Examples: >>> krishnamurthy_number(145) True >>> krishnamurthy_number(357) False """ if n == 0: return False sum_of_digits = 0 temp = n while temp != 0: sum_of_digits += _find_factorial(temp % 10) temp //= 10 return sum_of_digits == n
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/krishnamurthy_number.py", "license": "MIT License", "lines": 42, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/magic_number.py
""" 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 __future__ import annotations def magic_number(n: int) -> bool: """Check if n is a magic number (digital root equals 1). Args: n: The integer to check. Returns: True if the digital root of n is 1, False otherwise. Examples: >>> magic_number(1234) True >>> magic_number(111) False """ 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
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/magic_number.py", "license": "MIT License", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/modular_exponential.py
""" 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 def modular_exponential(base: int, exponent: int, mod: int) -> int: """Compute (base ^ exponent) % mod using binary exponentiation. Args: base: The base value. exponent: The exponent (must be non-negative). mod: The modulus. Returns: The result of (base ^ exponent) % mod. Raises: ValueError: If exponent is negative. Examples: >>> modular_exponential(5, 117, 19) 1 """ if exponent < 0: raise ValueError("Exponent must be positive.") base %= mod result = 1 while exponent > 0: if exponent & 1: result = (result * base) % mod exponent = exponent >> 1 base = (base * base) % mod return result
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/modular_exponential.py", "license": "MIT License", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/modular_inverse.py
""" 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) """ from __future__ import annotations def _extended_gcd(a: int, b: int) -> tuple[int, int, int]: """Compute the extended GCD of two integers. Args: a: First integer. b: Second integer. Returns: A tuple (s, t, g) where a * s + b * t = g = gcd(a, b). """ 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 - quotient * t return old_s, old_t, old_r def modular_inverse(a: int, m: int) -> int: """Find x such that a * x = 1 (mod m). Args: a: The integer to find the inverse of. m: The modulus (must be coprime with a). Returns: The modular multiplicative inverse of a modulo m. Raises: ValueError: If a and m are not coprime. Examples: >>> modular_inverse(2, 19) 10 """ s, _, g = _extended_gcd(a, m) if g != 1: raise ValueError("a and m must be coprime") return s % m
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/modular_inverse.py", "license": "MIT License", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/next_bigger.py
""" 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: O(n) where n is the number of digits Space: O(n) """ from __future__ import annotations def next_bigger(num: int) -> int: """Find the next higher number with the exact same digits. Args: num: A positive integer. Returns: The next higher number with the same digits, or -1 if no such number exists. Examples: >>> next_bigger(38276) 38627 >>> next_bigger(99999) -1 """ 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 pivot >= digits[swap_idx]: swap_idx -= 1 digits[swap_idx], digits[idx - 1] = digits[idx - 1], digits[swap_idx] digits[idx:] = digits[: idx - 1 : -1] return int("".join(str(x) for x in digits))
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/next_bigger.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/next_perfect_square.py
""" 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 find_next_square(sq: float) -> float: """Find the next perfect square after sq. Args: sq: A non-negative number to check. Returns: The next perfect square if sq is a perfect square, otherwise -1. Examples: >>> find_next_square(121) 144 >>> find_next_square(10) -1 """ root = sq**0.5 if root.is_integer(): return (root + 1) ** 2 return -1 def find_next_square2(sq: float) -> float: """Find the next perfect square using modulo check. Args: sq: A non-negative number to check. Returns: The next perfect square if sq is a perfect square, otherwise -1. Examples: >>> find_next_square2(121) 144 >>> find_next_square2(10) -1 """ root = sq**0.5 return -1 if root % 1 else (root + 1) ** 2
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/next_perfect_square.py", "license": "MIT License", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/nth_digit.py
""" 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(log n) for string conversion """ from __future__ import annotations def find_nth_digit(n: int) -> int: """Find the nth digit in the sequence of natural numbers. Args: n: The 1-based position of the digit to find. Returns: The digit at position n. Examples: >>> find_nth_digit(11) 0 """ 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])
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/nth_digit.py", "license": "MIT License", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/num_digits.py
""" 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 import math def num_digits(n: int) -> int: """Count the number of digits in an integer. Args: n: An integer (negative values use their absolute value). Returns: The number of digits in n. Examples: >>> num_digits(12) 2 >>> num_digits(0) 1 >>> num_digits(-254) 3 """ n = abs(n) if n == 0: return 1 return int(math.log10(n)) + 1
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/num_digits.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/num_perfect_squares.py
""" 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(sqrt(n)) Space: O(1) """ from __future__ import annotations import math def num_perfect_squares(number: int) -> int: """Find the minimum count of perfect squares that sum to number. Args: number: A positive integer. Returns: An integer between 1 and 4 representing the minimum count. Examples: >>> num_perfect_squares(9) 1 >>> num_perfect_squares(10) 2 >>> num_perfect_squares(12) 3 >>> num_perfect_squares(31) 4 """ 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): if int(math.sqrt(number - i**2)) ** 2 == number - i**2: return 2 return 3
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/num_perfect_squares.py", "license": "MIT License", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/polynomial.py
""" 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/Polynomial Complexity: Time: Varies by operation Space: O(number of monomials) """ from __future__ import annotations from collections.abc import Iterable from fractions import Fraction from functools import reduce from numbers import Rational class Monomial: """A monomial represented by a coefficient and variable-to-power mapping.""" def __init__( self, variables: dict[int, int], coeff: int | float | Fraction | None = None ) -> None: """Create a monomial with the given variables and coefficient. Args: variables: Dictionary mapping variable indices to their powers. coeff: The coefficient (defaults to 0 if empty, 1 otherwise). Examples: >>> Monomial({1: 1}) # (a_1)^1 >>> Monomial({1: 3, 2: 2}, 12) # 12(a_1)^3(a_2)^2 """ self.variables = dict() if coeff is None: coeff = Fraction(0, 1) if len(variables) == 0 else Fraction(1, 1) elif coeff == 0: self.coeff = Fraction(0, 1) return if len(variables) == 0: self.coeff = Monomial._rationalize_if_possible(coeff) return for i in variables: if variables[i] != 0: self.variables[i] = variables[i] self.coeff = Monomial._rationalize_if_possible(coeff) @staticmethod def _rationalize_if_possible( num: int | float | Fraction, ) -> Fraction | float: """Convert numbers to Fraction when possible. Args: num: A numeric value. Returns: A Fraction if the input is Rational, otherwise the original value. """ if isinstance(num, Rational): res = Fraction(num, 1) return Fraction(res.numerator, res.denominator) else: return num def equal_upto_scalar(self, other: object) -> bool: """Check if other is a monomial equivalent to self up to scalar multiple. Args: other: Another Monomial to compare. Returns: True if both have the same variables with the same powers. Raises: ValueError: If other is not a Monomial. """ if not isinstance(other, Monomial): raise ValueError("Can only compare monomials.") return other.variables == self.variables def __add__(self, other: int | float | Fraction) -> Monomial: """Add two monomials or a monomial with a scalar. Args: other: A Monomial, int, float, or Fraction to add. Returns: The resulting Monomial. Raises: ValueError: If monomials have different variables. """ if isinstance(other, (int, float, Fraction)): return self.__add__(Monomial({}, Monomial._rationalize_if_possible(other))) if not isinstance(other, Monomial): raise ValueError("Can only add monomials, ints, floats, or Fractions.") if self.variables == other.variables: mono = {i: self.variables[i] for i in self.variables} return Monomial( mono, Monomial._rationalize_if_possible(self.coeff + other.coeff) ).clean() raise ValueError( f"Cannot add {str(other)} to {self.__str__()} " "because they don't have same variables." ) def __eq__(self, other: object) -> bool: """Check equality of two monomials. Args: other: Another Monomial to compare. Returns: True if both monomials are equal. """ if not isinstance(other, Monomial): return NotImplemented return self.equal_upto_scalar(other) and self.coeff == other.coeff def __mul__(self, other: int | float | Fraction) -> Monomial: """Multiply two monomials or a monomial with a scalar. Args: other: A Monomial, int, float, or Fraction to multiply. Returns: The resulting Monomial. Raises: ValueError: If other is not a valid type. """ if isinstance(other, (float, int, Fraction)): mono = {i: self.variables[i] for i in self.variables} return Monomial( mono, Monomial._rationalize_if_possible(self.coeff * other) ).clean() if not isinstance(other, Monomial): raise ValueError("Can only multiply monomials, ints, floats, or Fractions.") else: mono = {i: self.variables[i] for i in self.variables} for i in other.variables: if i in mono: mono[i] += other.variables[i] else: mono[i] = other.variables[i] temp = dict() for k in mono: if mono[k] != 0: temp[k] = mono[k] return Monomial( temp, Monomial._rationalize_if_possible(self.coeff * other.coeff) ).clean() def inverse(self) -> Monomial: """Compute the multiplicative inverse of this monomial. Returns: The inverse Monomial. Raises: ValueError: If the coefficient is zero. """ mono = {i: self.variables[i] for i in self.variables if self.variables[i] != 0} for i in mono: mono[i] *= -1 if self.coeff == 0: raise ValueError("Coefficient must not be 0.") return Monomial(mono, Monomial._rationalize_if_possible(1 / self.coeff)).clean() def __truediv__(self, other: int | float | Fraction) -> Monomial: """Divide this monomial by another monomial or scalar. Args: other: A Monomial, int, float, or Fraction divisor. Returns: The resulting Monomial. Raises: ValueError: If dividing by zero. """ if isinstance(other, (int, float, Fraction)): mono = {i: self.variables[i] for i in self.variables} if other == 0: raise ValueError("Cannot divide by 0.") return Monomial( mono, Monomial._rationalize_if_possible(self.coeff / other) ).clean() o = other.inverse() return self.__mul__(o) def __floordiv__(self, other: int | float | Fraction) -> Monomial: """Floor division (same as true division for monomials). Args: other: A Monomial, int, float, or Fraction divisor. Returns: The resulting Monomial. """ return self.__truediv__(other) def clone(self) -> Monomial: """Create a deep copy of this monomial. Returns: A new Monomial with the same variables and coefficient. """ temp_variables = {i: self.variables[i] for i in self.variables} return Monomial( temp_variables, Monomial._rationalize_if_possible(self.coeff) ).clean() def clean(self) -> Monomial: """Remove variables with zero power. Returns: A cleaned Monomial. """ temp_variables = { i: self.variables[i] for i in self.variables if self.variables[i] != 0 } return Monomial(temp_variables, Monomial._rationalize_if_possible(self.coeff)) def __sub__(self, other: int | float | Fraction) -> Monomial: """Subtract a value from this monomial. Args: other: A Monomial, int, float, or Fraction to subtract. Returns: The resulting Monomial. Raises: ValueError: If monomials have different variables. """ if isinstance(other, (int, float, Fraction)): mono = { i: self.variables[i] for i in self.variables if self.variables[i] != 0 } if len(mono) != 0: raise ValueError("Can only subtract like monomials.") other_term = Monomial(mono, Monomial._rationalize_if_possible(other)) return self.__sub__(other_term) if not isinstance(other, Monomial): raise ValueError("Can only subtract monomials") return self.__add__(other.__mul__(Fraction(-1, 1))) def __hash__(self) -> int: """Hash based on the underlying variables. Returns: An integer hash value. """ arr = [] for i in sorted(self.variables): if self.variables[i] > 0: for _ in range(self.variables[i]): arr.append(i) return hash(tuple(arr)) def all_variables(self) -> set: """Get the set of all variable indices in this monomial. Returns: A set of variable indices. """ return set(sorted(self.variables.keys())) def substitute( self, substitutions: int | float | Fraction | dict[int, int | float | Fraction], ) -> Fraction: """Evaluate the monomial by substituting values for variables. Args: substitutions: A single value applied to all variables, or a dict mapping variable indices to values. Returns: The evaluated result. Raises: ValueError: If some variables are not given values. """ if isinstance(substitutions, (int, float, Fraction)): substitutions = { v: Monomial._rationalize_if_possible(substitutions) for v in self.all_variables() } else: if not self.all_variables().issubset(set(substitutions.keys())): raise ValueError("Some variables didn't receive their values.") if self.coeff == 0: return Fraction(0, 1) ans = Monomial._rationalize_if_possible(self.coeff) for k in self.variables: ans *= Monomial._rationalize_if_possible( substitutions[k] ** self.variables[k] ) return Monomial._rationalize_if_possible(ans) def __str__(self) -> str: """Get a string representation of the monomial. Returns: A human-readable string. """ if len(self.variables) == 0: return str(self.coeff) result = str(self.coeff) result += "(" for i in self.variables: temp = f"a_{str(i)}" if self.variables[i] > 1: temp = "(" + temp + f")**{self.variables[i]}" elif self.variables[i] < 0: temp = "(" + temp + f")**(-{-self.variables[i]})" elif self.variables[i] == 0: continue else: temp = "(" + temp + ")" result += temp return result + ")" class Polynomial: """A polynomial represented as a set of Monomial terms.""" def __init__( self, monomials: Iterable[int | float | Fraction | Monomial] ) -> None: """Create a polynomial from an iterable of monomials or scalars. Args: monomials: An iterable of Monomial, int, float, or Fraction values. Raises: ValueError: If an element is not a valid type. """ self.monomials: set = set() for m in monomials: if any(map(lambda x: isinstance(m, x), [int, float, Fraction])): self.monomials |= {Monomial({}, m)} elif isinstance(m, Monomial): self.monomials |= {m} else: raise ValueError( "Iterable should have monomials, int, float, or Fraction." ) self.monomials -= {Monomial({}, 0)} @staticmethod def _rationalize_if_possible( num: int | float | Fraction, ) -> Fraction | float: """Convert numbers to Fraction when possible. Args: num: A numeric value. Returns: A Fraction if the input is Rational, otherwise the original value. """ if isinstance(num, Rational): res = Fraction(num, 1) return Fraction(res.numerator, res.denominator) else: return num def __add__(self, other: int | float | Fraction | Monomial) -> Polynomial: """Add a polynomial, monomial, or scalar to this polynomial. Args: other: Value to add. Returns: The resulting Polynomial. Raises: ValueError: If other is not a valid type. """ if isinstance(other, (int, float, Fraction)): return self.__add__( Monomial({}, Polynomial._rationalize_if_possible(other)) ) elif isinstance(other, Monomial): monos = {m.clone() for m in self.monomials} for _own_monos in monos: if _own_monos.equal_upto_scalar(other): scalar = _own_monos.coeff monos -= {_own_monos} temp_variables = {i: other.variables[i] for i in other.variables} monos |= { Monomial( temp_variables, Polynomial._rationalize_if_possible(scalar + other.coeff), ) } return Polynomial([z for z in monos]) monos |= {other.clone()} return Polynomial([z for z in monos]) elif isinstance(other, Polynomial): temp = list(z for z in {m.clone() for m in self.all_monomials()}) p = Polynomial(temp) for o in other.all_monomials(): p = p.__add__(o.clone()) return p else: raise ValueError( "Can only add int, float, Fraction, Monomials, " "or Polynomials to Polynomials." ) def __sub__(self, other: int | float | Fraction | Monomial) -> Polynomial: """Subtract a polynomial, monomial, or scalar from this polynomial. Args: other: Value to subtract. Returns: The resulting Polynomial. Raises: ValueError: If other is not a valid type. """ if isinstance(other, (int, float, Fraction)): return self.__sub__( Monomial({}, Polynomial._rationalize_if_possible(other)) ) elif isinstance(other, Monomial): monos = {m.clone() for m in self.all_monomials()} for _own_monos in monos: if _own_monos.equal_upto_scalar(other): scalar = _own_monos.coeff monos -= {_own_monos} temp_variables = {i: other.variables[i] for i in other.variables} monos |= { Monomial( temp_variables, Polynomial._rationalize_if_possible(scalar - other.coeff), ) } return Polynomial([z for z in monos]) to_insert = other.clone() to_insert.coeff *= -1 monos |= {to_insert} return Polynomial([z for z in monos]) elif isinstance(other, Polynomial): p = Polynomial(list(z for z in {m.clone() for m in self.all_monomials()})) for o in other.all_monomials(): p = p.__sub__(o.clone()) return p else: raise ValueError( "Can only subtract int, float, Fraction, " "Monomials, or Polynomials from Polynomials." ) def __mul__(self, other: int | float | Fraction | Monomial) -> Polynomial: """Multiply this polynomial by another polynomial, monomial, or scalar. Args: other: Value to multiply by. Returns: The resulting Polynomial. Raises: ValueError: If other is not a valid type. """ if isinstance(other, (int, float, Fraction, Monomial)): result = Polynomial([]) monos = {m.clone() for m in self.all_monomials()} for m in monos: result = result.__add__(m.clone() * other) return result elif isinstance(other, Polynomial): temp_self = {m.clone() for m in self.all_monomials()} temp_other = {m.clone() for m in other.all_monomials()} result = Polynomial([]) for i in temp_self: for j in temp_other: result = result.__add__(i * j) return result else: raise ValueError( "Can only multiple int, float, Fraction, " "Monomials, or Polynomials with Polynomials." ) def __floordiv__(self, other: int | float | Fraction | Monomial) -> Polynomial: """Floor division (same as true division for polynomials). Args: other: Divisor value. Returns: The resulting Polynomial. """ return self.__truediv__(other) def __truediv__(self, other: int | float | Fraction | Monomial) -> Polynomial: """Divide this polynomial by another value. Args: other: Divisor (int, float, Fraction, Monomial, or Polynomial). Returns: The quotient Polynomial. Raises: ValueError: If other is not a valid type. """ if isinstance(other, (int, float, Fraction)): return self.__truediv__(Monomial({}, other)) elif isinstance(other, Monomial): poly_temp = reduce( lambda acc, val: acc + val, map(lambda x: x / other, [z for z in self.all_monomials()]), Polynomial([Monomial({}, 0)]), ) return poly_temp elif isinstance(other, Polynomial): quotient, remainder = self.poly_long_division(other) return quotient raise ValueError( "Can only divide a polynomial by an int, float, " "Fraction, Monomial, or Polynomial." ) def clone(self) -> Polynomial: """Create a deep copy of this polynomial. Returns: A new Polynomial with cloned monomials. """ return Polynomial(list({m.clone() for m in self.all_monomials()})) def variables(self) -> set: """Get all variable indices present in this polynomial. Returns: A set of variable indices. """ res = set() for i in self.all_monomials(): res |= {j for j in i.variables} res = list(res) return set(res) def all_monomials(self) -> Iterable[Monomial]: """Get all non-zero monomials in this polynomial. Returns: A set of Monomial terms. """ return {m for m in self.monomials if m != Monomial({}, 0)} def __eq__(self, other: object) -> bool: """Check equality of two polynomials. Args: other: Another Polynomial, Monomial, or scalar. Returns: True if both represent the same polynomial. Raises: ValueError: If other is not a valid type. """ if isinstance(other, (int, float, Fraction)): other_poly = Polynomial([Monomial({}, other)]) return self.__eq__(other_poly) elif isinstance(other, Monomial): return self.__eq__(Polynomial([other])) elif isinstance(other, Polynomial): return self.all_monomials() == other.all_monomials() else: raise ValueError( "Can only compare a polynomial with an int, " "float, Fraction, Monomial, or another Polynomial." ) def subs( self, substitutions: int | float | Fraction | dict[int, int | float | Fraction], ) -> int | float | Fraction: """Evaluate the polynomial by substituting values for variables. Args: substitutions: A single value applied to all variables, or a dict mapping variable indices to values. Returns: The evaluated result. Raises: ValueError: If some variables are not given values. """ if isinstance(substitutions, (int, float, Fraction)): substitutions = { i: Polynomial._rationalize_if_possible(substitutions) for i in set(self.variables()) } return self.subs(substitutions) elif not isinstance(substitutions, dict): raise ValueError("The substitutions should be a dictionary.") if not self.variables().issubset(set(substitutions.keys())): raise ValueError("Some variables didn't receive their values.") ans = 0 for m in self.all_monomials(): ans += Polynomial._rationalize_if_possible(m.substitute(substitutions)) return Polynomial._rationalize_if_possible(ans) def __str__(self) -> str: """Get a formatted string representation of the polynomial. Returns: A human-readable string. """ sorted_monos = sorted( self.all_monomials(), key=lambda m: sorted(m.variables.items(), reverse=True), reverse=True, ) return " + ".join(str(m) for m in sorted_monos if m.coeff != Fraction(0, 1)) def poly_long_division(self, other: Polynomial) -> tuple[Polynomial, Polynomial]: """Perform polynomial long division. Args: other: The divisor Polynomial. Returns: A tuple (quotient, remainder). Raises: ValueError: If other is not a Polynomial or is zero. """ if not isinstance(other, Polynomial): raise ValueError("Can only divide by another Polynomial.") if len(other.all_monomials()) == 0: raise ValueError("Cannot divide by zero polynomial.") quotient = Polynomial([]) remainder = self.clone() divisor_monos = sorted( other.all_monomials(), key=lambda m: sorted(m.variables.items(), reverse=True), reverse=True, ) divisor_lead = divisor_monos[0] while remainder.all_monomials() and max( remainder.variables(), default=-1 ) >= max(other.variables(), default=-1): remainder_monos = sorted( remainder.all_monomials(), key=lambda m: sorted(m.variables.items(), reverse=True), reverse=True, ) remainder_lead = remainder_monos[0] if not all( remainder_lead.variables.get(var, 0) >= divisor_lead.variables.get(var, 0) for var in divisor_lead.variables ): break lead_quotient = remainder_lead / divisor_lead quotient = quotient + Polynomial([lead_quotient]) remainder = remainder - (Polynomial([lead_quotient]) * other) return quotient, remainder
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/polynomial.py", "license": "MIT License", "lines": 574, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
keon/algorithms:algorithms/math/power.py
""" 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) recursive """ from __future__ import annotations def power(a: int, n: int, mod: int | None = None) -> int: """Compute a^n iteratively using binary exponentiation. Args: a: The base. n: The exponent. mod: Optional modulus for modular exponentiation. Returns: a^n, or a^n % mod if mod is specified. Examples: >>> power(2, 3) 8 >>> power(10, 3, 5) 0 """ 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 | None = None) -> int: """Compute a^n recursively using binary exponentiation. Args: a: The base. n: The exponent. mod: Optional modulus for modular exponentiation. Returns: a^n, or a^n % mod if mod is specified. Examples: >>> power_recur(2, 3) 8 """ if n == 0: ans = 1 elif n == 1: ans = a else: ans = power_recur(a, n // 2, mod) ans = ans * ans if n % 2: ans = ans * a if mod: ans %= mod return ans
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/power.py", "license": "MIT License", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/prime_check.py
""" 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: int) -> bool: """Check whether n is a prime number. Args: n: The integer to test. Returns: True if n is prime, False otherwise. Examples: >>> prime_check(7) True >>> prime_check(4) False """ 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 return True
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/prime_check.py", "license": "MIT License", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/primes_sieve_of_eratosthenes.py
""" 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 def get_primes(n: int) -> list[int]: """Return all primes less than n using the Sieve of Eratosthenes. Args: n: Upper bound (exclusive). Must be a positive integer. Returns: A sorted list of all primes less than n. Raises: ValueError: If n is not positive. Examples: >>> get_primes(7) [2, 3, 5, 7] """ 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) for i in range(sieve_size): if sieve[i]: value_at_i = i * 2 + 3 primes.append(value_at_i) for j in range(i, sieve_size, value_at_i): sieve[j] = False return primes
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/primes_sieve_of_eratosthenes.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
keon/algorithms:algorithms/math/pythagoras.py
""" 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__ import annotations def pythagoras( opposite: float | str, adjacent: float | str, hypotenuse: float | str ) -> str: """Compute the unknown side of a right triangle. Pass "?" as the unknown side to calculate it from the other two. Args: opposite: Length of the opposite side, or "?" if unknown. adjacent: Length of the adjacent side, or "?" if unknown. hypotenuse: Length of the hypotenuse, or "?" if unknown. Returns: A string describing the computed side and its value. Raises: ValueError: If the arguments are invalid. Examples: >>> pythagoras(3, 4, "?") 'Hypotenuse = 5.0' """ try: if opposite == "?": return "Opposite = " + str(((hypotenuse**2) - (adjacent**2)) ** 0.5) if adjacent == "?": return "Adjacent = " + str(((hypotenuse**2) - (opposite**2)) ** 0.5) if hypotenuse == "?": return "Hypotenuse = " + str(((opposite**2) + (adjacent**2)) ** 0.5) return "You already know the answer!" except Exception as err: raise ValueError("invalid argument(s) were given.") from err
{ "repo_id": "keon/algorithms", "file_path": "algorithms/math/pythagoras.py", "license": "MIT License", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation