Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,9 @@ venv.bak/

# mypy
.mypy_cache/

# Ruff
.ruff_cache/

# Local configuration files
*.local.*
58 changes: 58 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Commands

This project uses `uv` for dependency management and `just` as the command runner.

```bash
just sync # install/sync dependencies (uv sync --all-groups)
just lint # uv run ruff check . --fix && uv run ruff format .
just test # uv run pytest
uv run pytest tests/algorithm_theory/test_binary_search.py # run one test file
uv run pytest tests/algorithm_theory/test_binary_search.py::test_binary_search_iterative # run one test
uv add {package} # add a dependency
```

There is no separate build step; this is a pure Python (3.14+) library of algorithms with no runtime dependencies.

## Architecture

The repo is organized by topic into top-level directories, each containing implementation modules directly at the
top level (no `src/` layout). `pyproject.toml` sets `pythonpath = ["."]`, so both implementation and test code
import via the top-level package name, e.g. `from algorithm_theory.binary_search import binary_search_iterative`.

Three categories of top-level directories, per the root `README.md`:

- **`algorithm_theory/`** — canonical/fundamental algorithm approaches (e.g. binary/jump/linear search, bubble
sort).
- **`data_structures/`** — custom implementations of core data structures (binary tree, linked lists, queue,
stack, trie) that other topic directories' problems build on top of.
- **Topic/problem directories** (`arrays/`, `binary_search/`, `binary_tree/`, `circularly_linked_list/`,
`doubly_linked_list/`, `integers/`, `math_problems/`, `multi_dimensional_arrays/`, `n_ary_tree/`, `queues/`,
`singly_linked_lists/`, `stacks/`, `strings/`, `trie/`)

The problem description, constraints, and examples live as a
**doc comment directly on the function/class that solves it** (see any existing file, e.g.
`arrays/two_sum.py`, as the template when adding a new problem). Only when a file genuinely has multiple
top-level functions/classes for one problem (e.g. a brute-force and an optimized approach, like
`stacks/daily_temperatures.py`) does it use a module-level docstring for the shared problem statement plus a
short docstring per function for the approach-specific detail — a single-function file should never have both a module docstring and a redundant function docstring.

Tests live under `tests/<same-directory-name>/test_<module>.py`, mirroring the source layout 1:1 (e.g.
`algorithm_theory/binary_search.py` → `tests/algorithm_theory/test_binary_search.py`). `test_helpers/test_helpers.py`
holds shared builders/fixtures (e.g. `get_binary_search_tree`, `get_singly_linked_list`) used across multiple test
directories for constructing trees and linked lists — check there before writing new setup code for tree/list-based
tests.

Node/structure classes used across multiple directories (e.g. `binary_tree.tree_node.TreeNode`,
`data_structures.singly_linked_list_node.SinglyLinkedListNode`, `n_ary_tree.nary_tree_node.NaryTreeNode`) are
imported directly from their defining module rather than redefined per problem.

## Style

Ruff is configured in `pyproject.toml` (line length 100, target `py314`, rule sets `E, F, W, I, N, D`). Docstring
presence itself is not enforced (`D100-D107` ignored), but when docstrings are present their formatting is linted.
`tests/*` is exempt from docstring rules entirely. Solutions favor explicit, readable Python over terse one-liners
(stated explicitly in the root `README.md`).
46 changes: 18 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,27 @@
Various Data Structures and Algorithm Solutions in Python (3.x). Succinct Python one-liners are avoided in most solutions
to prevent obscuring the function and logic of the algorithms / data-structures.

* [Algorithm Theory](algorithm_theory/README.md)
* [Searches](algorithm_theory/README.md#searches)
* [Binary Search](algorithm_theory/README.md#binary-search)
* [Jump Search](algorithm_theory/README.md#jump-search)
* [Linear Search](algorithm_theory/README.md#linear-search)
* [Sorts](algorithm_theory/README.md#sorts)
* [Bubble Sort](algorithm_theory/README.md#bubble-sort)
* [Data Structures](data_structures/README.md)
* [Binary Tree](data_structures/README.md#binary-tree)
* [Circularly Linked List](data_structures/README.md#circularly-linked-list)
* [Doubly Linked List](data_structures/README.md#doubly-linked-list)
* [Singly Linked List](data_structures/README.md#singly-linked-list)
* [Queue](data_structures/README.md#queue)
* [Stack](data_structures/README.md#stack)
* [Trie](data_structures/README.md#trie)
* [Algorithm Theory](algorithm_theory/)
* [Data Structures](data_structures/)

## Algorithms

* [Arrays](arrays/README.md)
* [Binary Search](binary_search/README.md)
* [Binary Tree](binary_tree/README.md)
* [Circularly Linked Lists](circularly_linked_list/README.md)
* [Doubly Linked Lists](doubly_linked_list/README.md)
* [Integers](integers/README.md)
* [Matrices](multi_dimensional_arrays/README.md)
* [N-ary Tree](n_ary_tree/README.md)
* [Queues](queues/README.md)
* [Singly Linked Lists](singly_linked_lists/README.md)
* [Stacks](stacks/README.md)
* [Strings](strings/README.md)
* [Trie](trie/README.md)
* [Arrays](arrays/)
* [Binary Search](binary_search/)
* [Binary Tree](binary_tree/)
* [Circularly Linked Lists](circularly_linked_list/)
* [Doubly Linked Lists](doubly_linked_list/)
* [Integers](integers/)
* [Math Problems](math_problems/)
* [Matrices](multi_dimensional_arrays/)
* [N-ary Tree](n_ary_tree/)
* [Queues](queues/)
* [Singly Linked Lists](singly_linked_lists/)
* [Stacks](stacks/)
* [Strings](strings/)
* [Trie](trie/)

Each directory's problems and approaches are documented as doc comments directly in the corresponding `.py` files.

## Project Setup

Expand Down
138 changes: 0 additions & 138 deletions algorithm_theory/README.md

This file was deleted.

14 changes: 10 additions & 4 deletions algorithm_theory/binary_search.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
# Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval
# covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow
# the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or
# the interval is empty.
"""Binary Search

Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval
covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow
the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or
the interval is empty.
"""

from typing import Optional


def binary_search_iterative(array: [int], target: int) -> Optional[int]:
"""Narrow the [left, right] bounds by half each iteration until target is found or the bounds cross."""
left = 0
right = len(array) - 1

Expand All @@ -22,6 +27,7 @@ def binary_search_iterative(array: [int], target: int) -> Optional[int]:


def binary_search_recursive(array: [int], left: int, right: int, target: int) -> Optional[int]:
"""Recurse into the left or right sub-array each call until target is found or the bounds cross."""
if right >= left:
mid = int((left + right) / 2)

Expand Down
9 changes: 6 additions & 3 deletions algorithm_theory/bubble_sort.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in
# wrong order.
def bubble_sort(array: [int]) -> []:
"""Bubble Sort.

The simplest sorting algorithm, working by repeatedly swapping the adjacent elements if they are
in wrong order.

def bubble_sort(array: [int]) -> []:
Example: `[2, 1, 3] -> [1, 2, 3]`
"""
length = len(array)

# Return if nothing to sort
Expand Down
20 changes: 15 additions & 5 deletions algorithm_theory/jump_search.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
# Jump Search is a searching algorithm for sorted arrays. The basic idea is to check fewer elements (than linear search)
# by jumping ahead by fixed steps or skipping some elements in place of searching all elements.
#
# step size is m = √n.

import math
from typing import Optional

from algorithm_theory.linear_search import linear_search


def jump_search(array: [int], target: int) -> Optional[int]:
"""Jump Search (https://www.geeksforgeeks.org/jump-search/).

A searching algorithm for sorted arrays. The basic idea is to check fewer elements (than linear
search) by jumping ahead by fixed steps or skipping some elements in place of searching all elements.

For example, suppose we have an array arr[] of size n and block (to be jumped) size `m`. Then we search
at the indexes `arr[0]`, `arr[m]`, `arr[2m]…..arr[km]`, and so on. Once we find the interval
(`arr[km] < x < arr[(k+1)m]`), we perform a linear search operation from the index `km` to find `x`.

What is the optimal block size to be skipped?
In the worst case, we have to do `n/m` jumps and if the last checked value is greater than the element
to be searched for, we perform `m-1` comparisons more for linear search. Therefore the total number of
comparisons in the worst case will be `((n/m) + m-1)`. The value of the function `((n/m) + m-1)` will be
minimum when `m = √n`. Therefore, the best step size is `m = √n`. (Geeks For Geeks)
"""
length = len(array)
interval = int(math.sqrt(length))
index = interval - 1 # 0 Based
Expand Down
8 changes: 5 additions & 3 deletions algorithm_theory/linear_search.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from typing import Optional

# The most basic search. Start from the leftmost element of the array and one by one compare the target with each
# element of the array. If the target matches with an element, return the index.


def linear_search(array: [int], left: int, right: int, target: int) -> Optional[int]:
"""Linear Search.

The most basic search. Start from the leftmost element of the array and one by one compare the target
with each element of the array. If the target matches with an element, return the index.
"""
for index in range(left, right + 1):
if array[index] == target:
return index
Expand Down
12 changes: 10 additions & 2 deletions arrays/arrays_intersection.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
from typing import List
"""Intersection of Three Sorted Arrays.

Given three integer arrays arr1, arr2, and arr3 sorted in strictly increasing order, return a sorted array of
only the integers that appear in all three arrays.

# Leetcode 1213. Intersection of Three Sorted Arrays
Example: `arr1 = [1, 2, 3, 4, 5], arr2 = [1, 2, 5, 7, 9], arr3 = [1, 3, 4, 5, 8]` -> `[1, 5]`
"""

from typing import List


def arrays_intersection(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
"""Set-intersection approach across all three arrays."""
intersection = set(arr1)
intersection = intersection.intersection(arr2)
return list(intersection.intersection(arr3))


def arrays_intersection2(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
"""Three-pointer sweep exploiting the sorted order of each array."""
index1 = 0
index2 = 0
index3 = 0
Expand Down
9 changes: 9 additions & 0 deletions arrays/check_double.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@


def check_double(arr: List[int]) -> bool:
"""Check Double.

Given an array arr of integers, check if there exist two integers N and M such that N is the double of M (i.e.
N = 2 * M). More formally, check if there exist two indices i and j such that i != j and arr[i] == 2 * arr[j].

Example: `arr = [10, 2, 5, 3]` -> `True` (`N = 10` is the double of `M = 5`, since `10 = 2 * 5`)

Track seen values in a set and check for a value's double or half on each pass.
"""
elements = set()

for num in arr:
Expand Down
Loading
Loading