Algorithms (alnoms.dsa.algorithms)
The algorithm pillar provides precision implementations for complex computational problems.
🕸️ Graph Theory
Breadth‑First Search Paths.
Provides a breadth‑first search (BFS)–based shortest‑path finder for undirected graphs. BFS computes the shortest path in terms of number of edges from a designated source vertex to all reachable vertices.
Design Characteristics: - Computes unweighted shortest paths - Produces predecessor links and distance levels - Time Complexity: O(V + E) - Space Complexity: O(V)
BreadthFirstPaths
Computes BFS‑based shortest paths from a single source vertex.
This class performs a breadth‑first search from a specified source vertex and records both predecessor links and distance levels. BFS guarantees shortest paths in unweighted graphs.
Attributes:
| Name | Type | Description |
|---|---|---|
_s |
int
|
The source vertex. |
_marked |
List[bool]
|
Marks whether each vertex has been visited. |
_edge_to |
List[int]
|
Predecessor links for path reconstruction. |
_dist_to |
List[float]
|
Number of edges in the shortest path. |
Source code in src/alnoms/dsa/algorithms/graph/breadth_first_paths.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
__init__(G, s)
Initializes BFS search from a source vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
Graph
|
The graph to search. |
required |
s
|
int
|
The source vertex. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the source vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/breadth_first_paths.py
dist_to(v)
Returns the BFS shortest‑path distance to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex whose distance is requested. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Number of edges in the shortest path. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/breadth_first_paths.py
has_path_to(v)
Checks whether a path exists from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if reachable, otherwise False. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/breadth_first_paths.py
path_to(v)
Returns the shortest path from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The destination vertex. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Iterable[int]]
|
Optional[Iterable[int]]: A sequence of vertices forming the |
Optional[Iterable[int]]
|
shortest path, or None if no path exists. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/breadth_first_paths.py
Depth‑First Search Orderings.
Computes preorder, postorder, and reverse‑postorder vertex orderings for a directed graph using depth‑first search (DFS). These orderings are fundamental in algorithms such as topological sorting and strongly connected components.
Design Characteristics: - DFS‑based vertex ordering - Reverse postorder supports topological sorting in DAGs - Time Complexity: O(V + E) - Space Complexity: O(V)
DepthFirstOrder
Computes DFS‑based vertex orderings for a directed graph.
This class performs a full DFS over all vertices of a directed graph and records the reverse postorder sequence. Reverse postorder is particularly useful for topological sorting in directed acyclic graphs (DAGs).
Attributes:
| Name | Type | Description |
|---|---|---|
_marked |
List[bool]
|
Marks whether each vertex has been visited. |
_reverse_post |
Deque[int]
|
Vertices in reverse postorder. |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_order.py
__init__(G)
Initializes DFS order computation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
Digraph
|
The directed graph whose orderings are computed. |
required |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_order.py
reverse_post()
Returns vertices in reverse postorder.
Returns:
| Type | Description |
|---|---|
Iterable[int]
|
Iterable[int]: A sequence of vertices in reverse postorder. |
Depth‑First Search Paths.
Provides a depth‑first search (DFS)–based path finder for undirected graphs. Starting from a designated source vertex, the algorithm explores all reachable vertices and records predecessor links that allow path reconstruction.
Design Characteristics: - Computes reachability from a single source - Produces DFS tree predecessor links - Paths are not guaranteed to be shortest - Time Complexity: O(V + E) - Space Complexity: O(V)
DepthFirstPaths
Computes DFS‑based paths from a single source vertex.
This class performs a depth‑first search from a specified source vertex and records the predecessor of each visited vertex. These predecessor links allow reconstruction of any path from the source to a reachable vertex.
Attributes:
| Name | Type | Description |
|---|---|---|
_s |
int
|
The source vertex. |
_marked |
List[bool]
|
Marks whether each vertex has been visited. |
_edge_to |
List[int]
|
Predecessor links for path reconstruction. |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_paths.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
__init__(G, s)
Initializes DFS search from a source vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
Graph
|
The graph to search. |
required |
s
|
int
|
The source vertex. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the source vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_paths.py
has_path_to(v)
Checks whether a path exists from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if reachable, otherwise False. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_paths.py
path_to(v)
Returns a path from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The destination vertex. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Iterable[int]]
|
Optional[Iterable[int]]: A sequence of vertices forming a path |
Optional[Iterable[int]]
|
from the source to |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the vertex is out of bounds. |
Source code in src/alnoms/dsa/algorithms/graph/depth_first_paths.py
Dijkstra's Shortest Paths.
Implements the single‑source shortest‑path algorithm for edge‑weighted directed graphs with non‑negative edge weights. The algorithm computes the shortest path tree rooted at a specified source vertex using a binary heap–based priority queue.
Design Characteristics: - Supports arbitrary directed graphs with non‑negative weights - Produces shortest‑path distances and predecessor edges - Uses lazy deletion in the priority queue - Time Complexity: O(E log V) - Space Complexity: O(V)
DijkstraSP
Computes shortest paths in a weighted directed graph.
This class computes the shortest path from a single source vertex to all other vertices in an edge‑weighted digraph with non‑negative edge weights. Distances and predecessor edges are stored for subsequent queries.
Attributes:
| Name | Type | Description |
|---|---|---|
_dist_to |
List[float]
|
Shortest known distance to each vertex. |
_edge_to |
List[Optional[DirectedEdge]]
|
Last edge on the shortest known path to each vertex. |
_pq |
List[tuple]
|
Min‑heap storing (distance, vertex) pairs. |
Source code in src/alnoms/dsa/algorithms/graph/dijkstra_sp.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
__init__(G, s)
Initializes the shortest‑path computation from a source vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
EdgeWeightedDigraph
|
The input directed graph. |
required |
s
|
int
|
The source vertex. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any edge in the graph has a negative weight. |
Source code in src/alnoms/dsa/algorithms/graph/dijkstra_sp.py
dist_to(v)
Returns the shortest‑path distance to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex whose distance is requested. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The shortest distance, or infinity if unreachable. |
Source code in src/alnoms/dsa/algorithms/graph/dijkstra_sp.py
has_path_to(v)
Checks whether a path exists from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The vertex to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if a path exists, otherwise False. |
Source code in src/alnoms/dsa/algorithms/graph/dijkstra_sp.py
path_to(v)
Returns the shortest path from the source to a vertex.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The destination vertex. |
required |
Returns:
| Type | Description |
|---|---|
Optional[Iterable[DirectedEdge]]
|
Optional[Iterable[DirectedEdge]]: A sequence of edges forming |
Optional[Iterable[DirectedEdge]]
|
the shortest path, or None if no path exists. |
Source code in src/alnoms/dsa/algorithms/graph/dijkstra_sp.py
Topological Sorting.
Provides a topological ordering of a directed acyclic graph (DAG) using depth‑first search finishing times. The implementation relies on the reverse postorder of a DFS traversal. If the graph contains a cycle, the resulting order is not a valid topological sort, but the algorithm still produces an ordering based on DFS structure.
Design Characteristics: - O(V + E) time - Uses DFS reverse‑postorder - Assumes the input graph is a DAG unless validated externally
Classes:
| Name | Description |
|---|---|
Topological |
Computes a topological order of a directed graph. |
Topological
Computes a topological order of a directed graph.
The ordering is derived from the reverse postorder of a depth‑first search. This yields a valid topological order if and only if the graph is acyclic. Cycle detection is not performed here; callers should validate DAG properties externally if correctness is required.
Source code in src/alnoms/dsa/algorithms/graph/topological.py
__init__(G)
Initializes the topological sort computation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
G
|
Digraph
|
Directed graph on which to compute the ordering. |
required |
Source code in src/alnoms/dsa/algorithms/graph/topological.py
has_order()
Indicates whether a topological order is available.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if an order was computed. This does not guarantee |
bool
|
that the graph is acyclic; it only reflects that an ordering |
|
bool
|
exists based on DFS finishing times. |
Source code in src/alnoms/dsa/algorithms/graph/topological.py
order()
Returns the computed topological order.
Returns:
| Type | Description |
|---|---|
Iterable[int]
|
Iterable[int]: Vertices in topological order. |
🔢 Sorting & Searching
Bubble Sort.
Implements the classic bubble sort algorithm, which repeatedly scans the array and swaps adjacent elements that are out of order. This version includes the standard early‑termination optimization: if a full pass completes with no swaps, the array is already sorted. An optional visualization mode yields intermediate array states after each swap.
Design Characteristics: - In‑place sorting - Stable behavior - O(N²) average and worst‑case time - O(N) best‑case time on already sorted input - O(1) auxiliary space - Visualization mode yields swap‑step snapshots
Classes:
| Name | Description |
|---|---|
BubbleSort |
Static implementation of bubble sort. |
BubbleSort
Bubble sort implementation.
Repeatedly compares adjacent elements and swaps them if they are in the wrong order. The algorithm terminates early if a full pass completes without any swaps, making it efficient for nearly sorted input.
Source code in src/alnoms/dsa/algorithms/sorting/bubble_sort.py
bubble_sort(arr, visualize=False)
staticmethod
Sorts the input list using bubble sort.
If visualize is True, the function returns a generator that
yields the array state after each swap. Otherwise, it returns the
fully sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
List[Any]
|
The list to sort. |
required |
visualize
|
bool
|
Whether to yield intermediate states. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[Any], Generator[List[Any], None, None]]
|
Union[List[Any], Generator[List[Any], None, None]]: Sorted list or generator of intermediate states. |
Complexity
Source code in src/alnoms/dsa/algorithms/sorting/bubble_sort.py
Insertion Sort.
Implements the classic insertion sort algorithm, which builds the sorted array incrementally by inserting each element into its correct position relative to the already‑sorted prefix. The algorithm performs extremely well on partially sorted arrays and small subarrays. An optional visualization mode yields intermediate array states after each swap.
Design Characteristics: - In‑place sorting - Stable behavior - O(N) best‑case time on nearly sorted input - O(N²) worst‑case time - O(1) auxiliary space - Visualization mode yields swap‑step snapshots
Classes:
| Name | Description |
|---|---|
InsertionSort |
Static implementation of insertion sort. |
InsertionSort
Insertion sort implementation.
Builds the sorted array one element at a time by shifting larger elements to the right and inserting the current element into its correct position. Particularly effective for small or partially sorted datasets.
Source code in src/alnoms/dsa/algorithms/sorting/insertion_sort.py
insertion_sort(arr, visualize=False)
staticmethod
Sorts the input list using insertion sort.
If visualize is True, the function returns a generator that
yields the array state after each swap. Otherwise, it returns the
fully sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
List[Any]
|
The list to sort. |
required |
visualize
|
bool
|
Whether to yield intermediate states. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[Any], Generator[List[Any], None, None]]
|
Union[List[Any], Generator[List[Any], None, None]]: Sorted list or generator of intermediate states. |
Complexity
Source code in src/alnoms/dsa/algorithms/sorting/insertion_sort.py
Merge Sort.
Implements the classic divide‑and‑conquer merge sort algorithm using an auxiliary array for merging. The algorithm guarantees O(N log N) time regardless of input distribution and is stable by construction. An optional visualization mode yields intermediate array states after each merge operation.
Design Characteristics: - Stable sorting - Deterministic O(N log N) time - Requires O(N) auxiliary space - Visualization mode yields merge‑step snapshots
Classes:
| Name | Description |
|---|---|
MergeSort |
Static implementation of top‑down merge sort. |
MergeSort
Top‑down recursive merge sort implementation.
The algorithm recursively divides the array into halves, sorts each half, and merges them using an auxiliary array. This version supports visualization by yielding intermediate states after each merge step.
Source code in src/alnoms/dsa/algorithms/sorting/merge_sort.py
merge_sort(arr, visualize=False)
staticmethod
Sorts the input list using merge sort.
If visualize is True, the function returns a generator that
yields the array state after each merge operation. Otherwise, it
returns the fully sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
List[Any]
|
The list to sort. |
required |
visualize
|
bool
|
Whether to yield intermediate states. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[Any], Generator[List[Any], None, None]]
|
Union[List[Any], Generator[List[Any], None, None]]: Sorted list or generator of intermediate states. |
Complexity
Source code in src/alnoms/dsa/algorithms/sorting/merge_sort.py
Quick Sort (3‑Way Partitioning).
Implements Dijkstra’s 3‑way partitioning variant of Quicksort, which handles duplicate keys efficiently by dividing the array into three regions: less than, equal to, and greater than the pivot. This approach improves performance on inputs with many repeated values.
Design Characteristics: - In‑place sorting - Average‑case O(N log N) time - Worst‑case O(N²) time (rare with randomized input) - O(log N) recursion depth - Optional visualization mode yielding intermediate array states
Classes:
| Name | Description |
|---|---|
QuickSort |
Static implementation of 3‑way partitioning Quicksort. |
QuickSort
3‑way partitioning Quicksort implementation.
Uses Dijkstra’s partitioning strategy to efficiently handle arrays with many duplicate keys. The algorithm recursively sorts the subarrays containing elements less than and greater than the pivot.
Source code in src/alnoms/dsa/algorithms/sorting/quick_sort.py
quick_sort(arr, visualize=False)
staticmethod
Sorts the input list using 3‑way partitioning Quicksort.
If visualize is True, the function returns a generator that
yields the array state after each swap or partitioning step.
Otherwise, it returns the fully sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
List[Any]
|
The list to sort. |
required |
visualize
|
bool
|
Whether to yield intermediate states. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[Any], Generator[List[Any], None, None]]
|
Union[List[Any], Generator[List[Any], None, None]]: Sorted list or generator of intermediate states. |
Complexity
Source code in src/alnoms/dsa/algorithms/sorting/quick_sort.py
Selection Sort.
Provides a simple comparison‑based sorting algorithm that repeatedly selects the minimum element and swaps it into its correct position. This implementation supports optional step‑by‑step visualization via a generator interface.
Design Characteristics: - In‑place sorting - Deterministic O(N²) time - O(1) auxiliary space - Visualization mode yields intermediate array states
Classes:
| Name | Description |
|---|---|
SelectionSort |
Static implementation of the selection sort algorithm. |
SelectionSort
Selection sort implementation.
Repeatedly scans the unsorted portion of the array to find the minimum element and swaps it into its correct position. The algorithm is simple, stable in behavior, and useful for educational and demonstrative purposes.
Source code in src/alnoms/dsa/algorithms/sorting/selection_sort.py
selection_sort(arr, visualize=False)
staticmethod
Sorts the input list using selection sort.
If visualize is True, the function returns a generator that
yields the array state after each swap. Otherwise, it returns the
fully sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
List[Any]
|
The list to sort. |
required |
visualize
|
bool
|
Whether to yield intermediate states. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[Any], Generator[List[Any], None, None]]
|
Union[List[Any], Generator[List[Any], None, None]]: Sorted list or generator of intermediate states. |
Complexity
Source code in src/alnoms/dsa/algorithms/sorting/selection_sort.py
Binary Search Utilities.
Provides classic binary search operations on sorted arrays, including exact‑match search and rank computation. Both operations run in O(log N) time and assume that the input list is already sorted in ascending order.
Design Characteristics: - Deterministic O(log N) time - Works on any comparable key type - Rank operation supports arrays with duplicates - No side effects; functions operate on the input list as read‑only
Classes:
| Name | Description |
|---|---|
BinarySearch |
Static utilities for binary search and rank. |
BinarySearch
Binary search and rank utilities.
Implements exact‑match binary search and a left‑leaning rank operation that counts how many elements are strictly less than a given key. Both methods assume the input list is sorted.
Source code in src/alnoms/dsa/algorithms/searching/binary_search.py
rank(a, key)
staticmethod
Returns the number of elements strictly less than key.
Uses a left‑leaning binary search to find the first index at
which key could be inserted while maintaining sorted order.
This yields the count of elements smaller than key and works
efficiently even with many duplicates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
List[Any]
|
Sorted list to examine. |
required |
key
|
Any
|
Target key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Count of elements strictly less than |
Complexity
Source code in src/alnoms/dsa/algorithms/searching/binary_search.py
search(a, key)
staticmethod
Performs binary search for key in a sorted list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
List[Any]
|
Sorted list to search. |
required |
key
|
Any
|
Target key. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Index of |
Complexity
Source code in src/alnoms/dsa/algorithms/searching/binary_search.py
🎯 Pointers
Pointer‑Based Algorithms.
Provides classic two‑pointer techniques, including Floyd’s Tortoise‑and‑Hare cycle detection algorithm for singly linked lists. These algorithms rely on constant‑space pointer manipulation and are widely used in linked‑list processing and fast/slow traversal patterns.
Design Characteristics:
- O(1) auxiliary space
- O(N) cycle detection
- Works on any singly linked list with next references
Classes:
| Name | Description |
|---|---|
CycleDetector |
Implements Floyd’s cycle‑finding algorithm. |
CycleDetector
Cycle detection using Floyd’s Tortoise‑and‑Hare algorithm.
Uses two pointers moving at different speeds to determine whether a singly linked list contains a cycle. If the fast pointer ever meets the slow pointer, a cycle exists.
Source code in src/alnoms/dsa/algorithms/pointers/cycle_detector.py
has_cycle(head)
staticmethod
Detects whether a singly linked list contains a cycle.
The algorithm advances a slow pointer by one step and a fast pointer by two steps. If the list contains a cycle, the two pointers eventually meet. If the fast pointer reaches the end of the list, no cycle exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
head
|
Optional[Node]
|
Head of the singly linked list. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if a cycle exists, otherwise False. |