sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
karpathy/nanochat:dev/repackage_data_reference.py | """
Repackage the FinewebEdu-100B dataset into shards:
- each shard is ~100MB in size (after zstd compression)
- parquets are written with row group size of 1000
- shuffle the dataset
This will be uploaded to HuggingFace for hosting.
The big deal is that our DataLoader will be able to stream
the data and cache it alo... | {
"repo_id": "karpathy/nanochat",
"file_path": "dev/repackage_data_reference.py",
"license": "MIT License",
"lines": 83,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
karpathy/nanochat:nanochat/checkpoint_manager.py | """
Utilities for saving and loading model/optim/state checkpoints.
"""
import os
import re
import glob
import json
import logging
import torch
from nanochat.common import get_base_dir
from nanochat.gpt import GPT, GPTConfig
from nanochat.tokenizer import get_tokenizer
from nanochat.common import setup_default_logging... | {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/checkpoint_manager.py",
"license": "MIT License",
"lines": 178,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:nanochat/common.py | """
Common utilities for nanochat.
"""
import os
import re
import logging
import urllib.request
import torch
import torch.distributed as dist
from filelock import FileLock
class ColoredFormatter(logging.Formatter):
"""Custom formatter that adds colors to log messages."""
# ANSI color codes
COLORS = {
... | {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/common.py",
"license": "MIT License",
"lines": 227,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:nanochat/core_eval.py | """
Functions for evaluating the CORE metric, as described in the DCLM paper.
https://arxiv.org/abs/2406.11794
TODOs:
- All tasks ~match except for squad. We get 31% reference is 37%. Figure out why.
"""
import random
from jinja2 import Template
import torch
import torch.distributed as dist
# -----------------------... | {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/core_eval.py",
"license": "MIT License",
"lines": 228,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:nanochat/dataloader.py | """
Distributed dataloaders for pretraining.
BOS-aligned bestfit:
- Every row starts with BOS token
- Documents packed using best-fit algorithm to minimize cropping
- When no document fits remaining space, crops a document to fill exactly
- 100% utilization (no padding), ~35% tokens cropped at T=2048
Comp... | {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/dataloader.py",
"license": "MIT License",
"lines": 139,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:nanochat/dataset.py | """
The base/pretraining dataset is a set of parquet files.
This file contains utilities for:
- iterating over the parquet files and yielding documents from it
- download the files on demand if they are not on disk
For details of how the dataset was prepared, see `repackage_data_reference.py`.
"""
import os
import ar... | {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/dataset.py",
"license": "MIT License",
"lines": 110,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:nanochat/engine.py | """
Engine for efficient inference of our models.
Everything works around token sequences:
- The user can send token sequences to the engine
- The engine returns the next token
Notes:
- The engine knows nothing about tokenization, it's purely token id sequences.
The whole thing is made as efficient as possible.
"""
... | {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/engine.py",
"license": "MIT License",
"lines": 316,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:nanochat/execution.py | """
Sandboxed execution utilities for running Python code that comes out of an LLM.
Adapted from OpenAI HumanEval code:
https://github.com/openai/human-eval/blob/master/human_eval/execution.py
What is covered:
- Each execution runs in its own process (can be killed if it hangs or crashes)
- Execution is limited by a t... | {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/execution.py",
"license": "MIT License",
"lines": 283,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:nanochat/gpt.py | """
GPT model (rewrite, a lot simpler)
Notable features:
- rotary embeddings (and no positional embeddings)
- QK norm
- untied weights for token embedding and lm_head
- relu^2 activation in MLP
- norm after token embedding
- no learnable params in rmsnorm
- no bias in linear layers
- Group-Query Attention (GQA) support... | {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/gpt.py",
"license": "MIT License",
"lines": 401,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:nanochat/loss_eval.py | """
A number of functions that help with evaluating a base model.
"""
import math
import torch
import torch.distributed as dist
@torch.no_grad()
def evaluate_bpb(model, batches, steps, token_bytes):
"""
Instead of the naive 'mean loss', this function returns the bits per byte (bpb),
which is a tokenization... | {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/loss_eval.py",
"license": "MIT License",
"lines": 62,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:nanochat/report.py | """
Utilities for generating training report cards. More messy code than usual, will fix.
"""
import os
import re
import shutil
import subprocess
import socket
import datetime
import platform
import psutil
import torch
def run_command(cmd):
"""Run a shell command and return output, or None if it fails."""
try... | {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/report.py",
"license": "MIT License",
"lines": 367,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:nanochat/tokenizer.py | """
BPE Tokenizer in the style of GPT-4.
Two implementations are available:
1) HuggingFace Tokenizer that can do both training and inference but is really confusing
2) Our own RustBPE Tokenizer for training and tiktoken for efficient inference
"""
import os
import copy
from functools import lru_cache
SPECIAL_TOKENS ... | {
"repo_id": "karpathy/nanochat",
"file_path": "nanochat/tokenizer.py",
"license": "MIT License",
"lines": 353,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:scripts/base_eval.py | """
Unified evaluation script for base models.
Supports three evaluation modes (comma-separated):
--eval core : CORE metric (accuracy on ICL tasks)
--eval bpb : Bits per byte on train/val splits
--eval sample : Generate samples from the model
Default is all three: --eval core,bpb,sample
Examples:
... | {
"repo_id": "karpathy/nanochat",
"file_path": "scripts/base_eval.py",
"license": "MIT License",
"lines": 280,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:scripts/base_train.py | """
Train model. From root directory of the project, run as:
python -m scripts.base_train
or distributed as:
torchrun --nproc_per_node=8 -m scripts.base_train
If you are only on CPU/Macbook, you'll want to train a much much smaller LLM. Example:
python -m scripts.base_train --depth=4 --max-seq-len=512 --device-batc... | {
"repo_id": "karpathy/nanochat",
"file_path": "scripts/base_train.py",
"license": "MIT License",
"lines": 541,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:scripts/chat_cli.py | """
New and upgraded chat mode because a lot of the code has changed since the last one.
Intended to be run single GPU only atm:
python -m scripts.chat_cli
"""
import argparse
import torch
from nanochat.common import compute_init, autodetect_device_type
from contextlib import nullcontext
from nanochat.engine import En... | {
"repo_id": "karpathy/nanochat",
"file_path": "scripts/chat_cli.py",
"license": "MIT License",
"lines": 89,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:scripts/chat_eval.py | """
Evaluate the Chat model.
All the generic code lives here, and all the evaluation-specific
code lives in nanochat directory and is imported from here.
Example runs:
python -m scripts.chat_eval -a ARC-Easy
torchrun --nproc_per_node=8 -m scripts.chat_eval -- -a ARC-Easy
"""
import argparse
from functools import part... | {
"repo_id": "karpathy/nanochat",
"file_path": "scripts/chat_eval.py",
"license": "MIT License",
"lines": 220,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:scripts/chat_rl.py | """
Reinforcement learning on GSM8K via "GRPO".
I put GRPO in quotes because we actually end up with something a lot
simpler and more similar to just REINFORCE:
1) Delete trust region, so there is no KL regularization to a reference model
2) We are on policy, so there's no need for PPO ratio+clip.
3) We use DAPO styl... | {
"repo_id": "karpathy/nanochat",
"file_path": "scripts/chat_rl.py",
"license": "MIT License",
"lines": 308,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:scripts/chat_sft.py | """
Supervised fine-tuning (SFT) the model.
Run as:
python -m scripts.chat_sft
Or torchrun for training:
torchrun --standalone --nproc_per_node=8 -m scripts.chat_sft -- --device-batch-size=16
"""
import gc
import argparse
import os
os.environ["PYTORCH_ALLOC_CONF"] = "expandable_segments:True"
import time
import wan... | {
"repo_id": "karpathy/nanochat",
"file_path": "scripts/chat_sft.py",
"license": "MIT License",
"lines": 450,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:scripts/chat_web.py | #!/usr/bin/env python3
"""
Unified web chat server - serves both UI and API from a single FastAPI instance.
Uses data parallelism to distribute requests across multiple GPUs. Each GPU loads
a full copy of the model, and incoming requests are distributed to available workers.
Launch examples:
- single available GPU (... | {
"repo_id": "karpathy/nanochat",
"file_path": "scripts/chat_web.py",
"license": "MIT License",
"lines": 357,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:scripts/tok_train.py | """
Train a tokenizer using our own BPE Tokenizer library.
In the style of GPT-4 tokenizer.
"""
import os
import time
import argparse
import torch
from nanochat.tokenizer import RustBPETokenizer
from nanochat.common import get_base_dir
from nanochat.dataset import parquets_iter_batched
# ------------------------------... | {
"repo_id": "karpathy/nanochat",
"file_path": "scripts/tok_train.py",
"license": "MIT License",
"lines": 97,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
karpathy/nanochat:tasks/arc.py | """
The ARC dataset from Allen AI.
https://huggingface.co/datasets/allenai/ai2_arc
"""
from datasets import load_dataset
from tasks.common import Task, render_mc
class ARC(Task):
def __init__(self, subset, split, **kwargs):
super().__init__(**kwargs)
assert subset in ["ARC-Easy", "ARC-Challenge"]... | {
"repo_id": "karpathy/nanochat",
"file_path": "tasks/arc.py",
"license": "MIT License",
"lines": 41,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
karpathy/nanochat:tasks/common.py | """
Base class for all Tasks.
A Task is basically a dataset of conversations, together with some
metadata and often also evaluation criteria.
Example tasks: MMLU, ARC-Easy, ARC-Challenge, GSM8K, HumanEval, SmolTalk.
"""
import random
class Task:
"""
Base class of a Task. Allows for lightweight slicing of the ... | {
"repo_id": "karpathy/nanochat",
"file_path": "tasks/common.py",
"license": "MIT License",
"lines": 120,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
karpathy/nanochat:tasks/gsm8k.py | """
GSM8K evaluation.
https://huggingface.co/datasets/openai/gsm8k
Example problem instance:
Question:
Weng earns $12 an hour for babysitting. Yesterday, she just did 50 minutes of babysitting. How much did she earn?
Answer:
Weng earns 12/60 = $<<12/60=0.2>>0.2 per minute.
Working 50 minutes, she earned 0.2 x 50 = $<... | {
"repo_id": "karpathy/nanochat",
"file_path": "tasks/gsm8k.py",
"license": "MIT License",
"lines": 102,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
karpathy/nanochat:tasks/humaneval.py | """
Evaluate the Chat model on HumanEval dataset.
Btw this dataset is a misnomer and has nothing to do with humans.
It is a coding benchmark.
"""
import re
from datasets import load_dataset
from nanochat.execution import execute_code
from tasks.common import Task
def extract_imports(prompt):
"""Extract import sta... | {
"repo_id": "karpathy/nanochat",
"file_path": "tasks/humaneval.py",
"license": "MIT License",
"lines": 84,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
karpathy/nanochat:tasks/smoltalk.py | """
SmolTalk by HuggingFace. Good "general" conversational dataset.
https://huggingface.co/datasets/HuggingFaceTB/smol-smoltalk
We use the "smol" version, which is more appropriate for smaller models.
"""
from datasets import load_dataset
from tasks.common import Task
class SmolTalk(Task):
""" smol-smoltalk datas... | {
"repo_id": "karpathy/nanochat",
"file_path": "tasks/smoltalk.py",
"license": "MIT License",
"lines": 41,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
keon/algorithms:algorithms/data_structures/veb_tree.py | """
Van Emde Boas Tree (vEB Tree) / van Emde Boas priority queue
Reference: https://en.wikipedia.org/wiki/Van_Emde_Boas_tree
A van Emde Boas tree is a recursive data structure for storing integers
from a fixed universe [0, u - 1], where u is a power of 2.
Time complexity:
insert / delete / successor / member : O... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/data_structures/veb_tree.py",
"license": "MIT License",
"lines": 213,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:tests/test_veb_tree.py | import unittest
from algorithms.data_structures.veb_tree import VEBTree
class TestVEBTree(unittest.TestCase):
def setUp(self):
self.veb = VEBTree(16)
def test_insert_and_member(self):
values = [2, 3, 4, 7, 14]
for v in values:
self.veb.insert(v)
for v in values:
... | {
"repo_id": "keon/algorithms",
"file_path": "tests/test_veb_tree.py",
"license": "MIT License",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
keon/algorithms:algorithms/data_structures/sqrt_decomposition.py | """
Square Root (Sqrt) Decomposition
Divides an array into blocks of size βn to allow O(βn) range queries and
point updates β a simple alternative to segment trees for range-aggregate
problems.
Supports:
- **Range sum queries** in O(βn).
- **Point updates** in O(1).
Reference: https://cp-algorithms.com/data_structur... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/data_structures/sqrt_decomposition.py",
"license": "MIT License",
"lines": 99,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/graph/dijkstra_heapq.py | """
Dijkstra's Shortest-Path Algorithm (Heap-Optimised)
Computes single-source shortest paths in a graph with non-negative edge
weights using a min-heap (priority queue) for efficient vertex selection.
This adjacency-list implementation is faster than the O(VΒ²) matrix version
for sparse graphs.
Reference: https://en... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/graph/dijkstra_heapq.py",
"license": "MIT License",
"lines": 69,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/math/goldbach.py | """
Goldbach's Conjecture
Every even integer greater than 2 can be expressed as the sum of two primes.
This module provides a function to find such a pair of primes and a helper
to verify the conjecture over a range.
Reference: https://en.wikipedia.org/wiki/Goldbach%27s_conjecture
Complexity:
Time: O(n * sqrt(n... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/math/goldbach.py",
"license": "MIT License",
"lines": 72,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/tree/binary_tree_views.py | """
Binary Tree Views
Compute different "views" of a binary tree β the nodes visible when looking
at the tree from a particular direction.
- **Left view**: first node at each level (leftmost).
- **Right view**: last node at each level (rightmost).
- **Top view**: nodes visible when looking from above.
- **Bottom view... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/tree/binary_tree_views.py",
"license": "MIT License",
"lines": 127,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:tests/test_issue_fixes.py | """Tests for algorithms added to resolve open GitHub issues."""
from __future__ import annotations
import unittest
from algorithms.common.tree_node import TreeNode
from algorithms.data_structures import SqrtDecomposition
from algorithms.graph.dijkstra_heapq import dijkstra
from algorithms.math.goldbach import goldba... | {
"repo_id": "keon/algorithms",
"file_path": "tests/test_issue_fixes.py",
"license": "MIT License",
"lines": 180,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
keon/algorithms:algorithms/backtracking/minimax.py | """Minimax β game-tree search with alpha-beta pruning.
The minimax algorithm finds the optimal move for a two-player zero-sum
game. Alpha-beta pruning reduces the search space by eliminating branches
that cannot influence the final decision.
Inspired by PR #860 (DD2480-group16).
"""
from __future__ import annotation... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/minimax.py",
"license": "MIT License",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
keon/algorithms:algorithms/bit_manipulation/gray_code.py | """Gray code β generate n-bit Gray code sequences.
A Gray code is an ordering of binary numbers such that successive values
differ in exactly one bit. Used in error correction and rotary encoders.
Inspired by PR #932 (Simranstha045).
"""
from __future__ import annotations
def gray_code(n: int) -> list[int]:
""... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/gray_code.py",
"license": "MIT License",
"lines": 23,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/data_structures/kd_tree.py | """KD-tree β a space-partitioning tree for k-dimensional points.
Supports efficient nearest-neighbour and range queries.
Inspired by PR #915 (gjones1077).
"""
from __future__ import annotations
import math
from typing import Any
class KDNode:
"""A single node in a KD-tree."""
__slots__ = ("point", "left"... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/data_structures/kd_tree.py",
"license": "MIT License",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
keon/algorithms:algorithms/dynamic_programming/bitmask.py | """Bitmask dynamic programming β Travelling Salesman Problem (TSP).
Uses DP with bitmask to find the minimum-cost Hamiltonian cycle in a
weighted graph. The state (visited_mask, current_city) encodes which
cities have been visited and where we are now.
Time: O(2^n * n^2). Space: O(2^n * n).
Inspired by PR #855 (Ama... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/dynamic_programming/bitmask.py",
"license": "MIT License",
"lines": 34,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/dynamic_programming/count_paths_dp.py | """Count paths in a grid β recursive, memoized, and bottom-up DP.
Count the number of unique paths from the top-left to the bottom-right
of an m x n grid, moving only right or down.
Inspired by PR #857 (c-cret).
"""
from __future__ import annotations
from functools import cache
def count_paths_recursive(m: int, n... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/dynamic_programming/count_paths_dp.py",
"license": "MIT License",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/graph/blossom.py | """Edmonds' blossom algorithm β maximum cardinality matching.
Finds a maximum matching in a general (non-bipartite) undirected graph.
The algorithm handles odd-length cycles ("blossoms") by contracting them
and recursing.
Time: O(V^2 * E).
Inspired by PR #826 (abhishekiitm).
"""
from __future__ import annotations
... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/graph/blossom.py",
"license": "MIT License",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
keon/algorithms:algorithms/math/linear_regression.py | """Simple linear regression β fit a line to (x, y) data.
Computes the ordinary least-squares regression line y = mx + b
without external libraries.
Inspired by PR #871 (MakanFar).
"""
from __future__ import annotations
import math
def linear_regression(x: list[float], y: list[float]) -> tuple[float, float]:
"... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/math/linear_regression.py",
"license": "MIT License",
"lines": 49,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
keon/algorithms:algorithms/math/manhattan_distance.py | """Manhattan distance β L1 distance between two points.
Also known as taxicab distance or city-block distance, it is the sum
of absolute differences of coordinates.
Inspired by PR #877 (ChinZhengSheng).
"""
from __future__ import annotations
def manhattan_distance(a: tuple[float, ...], b: tuple[float, ...]) -> flo... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/math/manhattan_distance.py",
"license": "MIT License",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/math/polynomial_division.py | """Polynomial long division.
Divide polynomial *dividend* by *divisor* and return (quotient, remainder).
Polynomials are represented as lists of coefficients from highest to lowest
degree. E.g. [1, -3, 2] represents x^2 - 3x + 2.
Inspired by PR #840 (KTH-Software-Engineering-DD2480).
"""
from __future__ import anno... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/math/polynomial_division.py",
"license": "MIT License",
"lines": 36,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
keon/algorithms:algorithms/searching/exponential_search.py | """Exponential search β locate an element in a sorted array.
First finds a range where the target may lie by doubling the index,
then performs binary search within that range. Useful when the target
is near the beginning of a large or unbounded list.
Time: O(log i) where i is the index of the target.
Inspired by PR ... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/searching/exponential_search.py",
"license": "MIT License",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
keon/algorithms:algorithms/searching/sentinel_search.py | """Sentinel linear search β a small optimisation over naive linear search.
By placing the target at the end of the array (as a sentinel), we can
remove the bounds check from the inner loop, roughly halving comparisons.
Time: O(n) β same asymptotic complexity but fewer comparisons in practice.
Inspired by PR #907 (Ab... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/searching/sentinel_search.py",
"license": "MIT License",
"lines": 23,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
keon/algorithms:algorithms/string/alphabet_board_path.py | """Alphabet board path β find moves on a 5x5+1 letter board.
Given a board where 'a'-'z' are laid out in rows of 5:
a b c d e
f g h i j
k l m n o
p q r s t
u v w x y
z
Return the sequence of moves (U/D/L/R/!) to spell a target word
starting from 'a'.
Inspired by PR #897 (chnttx).
"""
from __... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/string/alphabet_board_path.py",
"license": "MIT License",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/string/manacher.py | """Manacher's algorithm β find the longest palindromic substring in O(n).
Manacher's algorithm uses the symmetry of palindromes to avoid redundant
comparisons, achieving linear time. It transforms the input to handle
both odd- and even-length palindromes uniformly.
Inspired by PR #931 (Simranstha045).
"""
def manac... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/string/manacher.py",
"license": "MIT License",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
keon/algorithms:algorithms/string/swap_characters.py | """Swap characters β check if two strings can be made equal by one swap.
Given two strings of equal length, determine whether exactly one swap
of two characters in the first string can make it equal to the second.
Inspired by PR #890 (Thejas-1).
"""
from __future__ import annotations
def can_swap_to_equal(s: str, ... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/string/swap_characters.py",
"license": "MIT License",
"lines": 12,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/string/z_algorithm.py | """Z-algorithm β linear-time pattern matching via the Z-array.
The Z-array for a string S stores at Z[i] the length of the longest
substring starting at S[i] that is also a prefix of S. By concatenating
pattern + '$' + text, occurrences of the pattern correspond to positions
where Z[i] == len(pattern).
Inspired by PR... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/string/z_algorithm.py",
"license": "MIT License",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
keon/algorithms:tests/test_community_algorithms.py | """Tests for community-contributed algorithms.
Covers algorithms adopted from open PRs and implemented to match
the repo's code standards.
"""
from __future__ import annotations
import unittest
from algorithms.backtracking.minimax import minimax
from algorithms.bit_manipulation.gray_code import gray_code, gray_to_b... | {
"repo_id": "keon/algorithms",
"file_path": "tests/test_community_algorithms.py",
"license": "MIT License",
"lines": 258,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
keon/algorithms:algorithms/array/delete_nth.py | """
Delete Nth Occurrence
Given a list and a number N, create a new list that contains each element
of the original list at most N times, without reordering.
Reference: https://www.geeksforgeeks.org/remove-duplicates-from-an-array/
Complexity:
delete_nth_naive:
Time: O(n^2) due to list.count()
S... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/delete_nth.py",
"license": "MIT License",
"lines": 49,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/flatten.py | """
Flatten Arrays
Given an array that may contain nested arrays, produce a single
flat resultant array.
Reference: https://en.wikipedia.org/wiki/Flatten_(higher-order_function)
Complexity:
Time: O(n) where n is the total number of elements
Space: O(n)
"""
from __future__ import annotations
from collectio... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/flatten.py",
"license": "MIT License",
"lines": 46,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/garage.py | """
Garage Parking Rearrangement
There is a parking lot with only one empty spot (represented by 0). Given the
initial and final states, find the minimum number of moves to rearrange the lot.
Each move swaps a car into the empty spot.
Reference: https://en.wikipedia.org/wiki/15_puzzle
Complexity:
Time: O(n^2) w... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/garage.py",
"license": "MIT License",
"lines": 43,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/josephus.py | """
Josephus Problem
People sit in a circular fashion; every k-th person is eliminated until
everyone has been removed. Yield the elimination order.
Reference: https://en.wikipedia.org/wiki/Josephus_problem
Complexity:
Time: O(n^2) due to list.pop at arbitrary index
Space: O(1) auxiliary (yields in-place)
"... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/josephus.py",
"license": "MIT License",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/limit.py | """
Limit Array Values
Filter an array to include only elements within a specified minimum and
maximum range (inclusive).
Reference: https://en.wikipedia.org/wiki/Clipping_(signal_processing)
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
def limit(
array: list[int],
mi... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/limit.py",
"license": "MIT License",
"lines": 33,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/longest_non_repeat.py | """
Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating
characters. Multiple algorithm variants are provided.
Reference: https://leetcode.com/problems/longest-substring-without-repeating-characters/
Complexity:
Time: O(n) for all variants
... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/longest_non_repeat.py",
"license": "MIT License",
"lines": 120,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/max_ones_index.py | """
Max Ones Index
Find the index of the 0 that, when replaced with 1, produces the longest
continuous sequence of 1s in a binary array. Returns -1 if no 0 exists.
Reference: https://www.geeksforgeeks.org/find-index-0-replaced-1-get-longest-continuous-sequence-1s-binary-array/
Complexity:
Time: O(n)
Space: ... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/max_ones_index.py",
"license": "MIT License",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/merge_intervals.py | """
Merge Intervals
Given a collection of intervals, merge all overlapping intervals into a
consolidated set.
Reference: https://en.wikipedia.org/wiki/Interval_(mathematics)
Complexity:
Time: O(n log n) due to sorting
Space: O(n)
"""
from __future__ import annotations
class Interval:
"""A numeric int... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/merge_intervals.py",
"license": "MIT License",
"lines": 94,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/missing_ranges.py | """
Missing Ranges
Find the ranges of numbers that are missing between a given low and high
bound, given a sorted array of integers.
Reference: https://leetcode.com/problems/missing-ranges/
Complexity:
Time: O(n)
Space: O(n) for the result list
"""
from __future__ import annotations
def missing_ranges(ar... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/missing_ranges.py",
"license": "MIT License",
"lines": 33,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/move_zeros.py | """
Move Zeros
Move all zeros in an array to the end while preserving the relative order
of the non-zero (and non-integer-zero) elements.
Reference: https://leetcode.com/problems/move-zeroes/
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
from typing import Any
def move_zeros(... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/move_zeros.py",
"license": "MIT License",
"lines": 31,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/n_sum.py | """
N-Sum
Given an array of integers, find all unique n-tuples that sum to a target
value. Supports custom sum, comparison, and equality closures for advanced
use cases with non-integer elements.
Reference: https://leetcode.com/problems/4sum/
Complexity:
Time: O(n^(k-1)) where k is the tuple size
Space: O(n... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/n_sum.py",
"license": "MIT License",
"lines": 108,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
keon/algorithms:algorithms/array/plus_one.py | """
Plus One
Given a non-negative number represented as an array of digits (big-endian),
add one to the number and return the resulting digit array.
Reference: https://leetcode.com/problems/plus-one/
Complexity:
Time: O(n)
Space: O(n) for v1, O(1) auxiliary for v2 and v3
"""
from __future__ import annotati... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/plus_one.py",
"license": "MIT License",
"lines": 67,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/remove_duplicates.py | """
Remove Duplicates
Remove duplicate elements from an array while preserving the original order.
Handles both hashable and unhashable items.
Reference: https://en.wikipedia.org/wiki/Duplicate_code
Complexity:
Time: O(n) for hashable items / O(n^2) worst case for unhashable items
Space: O(n)
"""
from __fu... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/remove_duplicates.py",
"license": "MIT License",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/rotate.py | """
Rotate Array
Rotate an array of n elements to the right by k steps.
Three algorithm variants are provided with different time complexities.
Reference: https://leetcode.com/problems/rotate-array/
Complexity:
rotate_v1: Time O(n*k), Space O(n)
rotate_v2: Time O(n), Space O(n)
rotate_v3: Time O(n), ... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/rotate.py",
"license": "MIT License",
"lines": 69,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/summarize_ranges.py | """
Summarize Ranges
Given a sorted integer array without duplicates, return the summary of its
ranges as a list of (start, end) tuples.
Reference: https://leetcode.com/problems/summary-ranges/
Complexity:
Time: O(n)
Space: O(n) for the result list
"""
from __future__ import annotations
def summarize_ran... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/summarize_ranges.py",
"license": "MIT License",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/three_sum.py | """
Three Sum
Given an array of integers, find all unique triplets that sum to zero
using the two-pointer technique.
Reference: https://leetcode.com/problems/3sum/
Complexity:
Time: O(n^2)
Space: O(n) for the result set
"""
from __future__ import annotations
def three_sum(array: list[int]) -> set[tuple[i... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/three_sum.py",
"license": "MIT License",
"lines": 41,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/top_1.py | """
Top 1 (Mode)
Find the most frequently occurring value(s) in an array. When multiple
values share the highest frequency, all are returned.
Reference: https://en.wikipedia.org/wiki/Mode_(statistics)
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
from typing import Any
def to... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/top_1.py",
"license": "MIT License",
"lines": 33,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/trimmean.py | """
Trimmed Mean
Compute the mean of an array after discarding a given percentage of the
highest and lowest values. Useful for robust averaging in scoring systems.
Reference: https://en.wikipedia.org/wiki/Truncated_mean
Complexity:
Time: O(n log n) due to sorting
Space: O(n) for the trimmed copy
"""
from _... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/trimmean.py",
"license": "MIT License",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/array/two_sum.py | """
Two Sum
Given an array of integers and a target sum, return the indices of the two
numbers that add up to the target.
Reference: https://leetcode.com/problems/two-sum/
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
def two_sum(array: list[int], target: int) -> tuple[int, in... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/array/two_sum.py",
"license": "MIT License",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/add_operators.py | """
Expression Add Operators
Given a string of digits and a target value, return all possibilities to
insert binary operators (+, -, *) between the digits so they evaluate to
the target value.
Reference: https://leetcode.com/problems/expression-add-operators/
Complexity:
Time: O(4^n) worst
Space: O(n) recur... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/add_operators.py",
"license": "MIT License",
"lines": 75,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
keon/algorithms:algorithms/backtracking/anagram.py | """
Anagram Checker
Given two strings, determine if they are anagrams of each other (i.e. one
can be rearranged to form the other).
Reference: https://en.wikipedia.org/wiki/Anagram
Complexity:
Time: O(n) where n is the length of the strings
Space: O(1) fixed 26-character alphabet
"""
from __future__ import... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/anagram.py",
"license": "MIT License",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/array_sum_combinations.py | """
Array Sum Combinations
Given three arrays and a target sum, find all three-element combinations
(one element from each array) that add up to the target.
Reference: https://en.wikipedia.org/wiki/Subset_sum_problem
Complexity:
Time: O(n^3) brute-force product of three arrays
Space: O(k) where k is the num... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/array_sum_combinations.py",
"license": "MIT License",
"lines": 93,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
keon/algorithms:algorithms/backtracking/combination_sum.py | """
Combination Sum
Given a set of candidate numbers (without duplicates) and a target number,
find all unique combinations where the candidate numbers sum to the target.
The same number may be chosen an unlimited number of times.
Reference: https://leetcode.com/problems/combination-sum/
Complexity:
Time: O(n^(... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/combination_sum.py",
"license": "MIT License",
"lines": 41,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/factor_combinations.py | """
Factor Combinations
Given an integer n, return all possible combinations of its factors.
Factors should be greater than 1 and less than n.
Reference: https://leetcode.com/problems/factor-combinations/
Complexity:
Time: O(n * log(n)) approximate
Space: O(log(n)) recursion depth
"""
from __future__ impor... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/factor_combinations.py",
"license": "MIT License",
"lines": 55,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/find_words.py | """
Word Search II
Given a board of characters and a list of words, find all words that can
be constructed from adjacent cells (horizontally or vertically). Each cell
may only be used once per word. Uses a trie for efficient prefix matching.
Reference: https://leetcode.com/problems/word-search-ii/
Complexity:
Ti... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/find_words.py",
"license": "MIT License",
"lines": 69,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
keon/algorithms:algorithms/backtracking/generate_abbreviations.py | """
Generalized Abbreviations
Given a word, return all possible generalized abbreviations. Each
abbreviation replaces contiguous substrings with their lengths.
Reference: https://leetcode.com/problems/generalized-abbreviation/
Complexity:
Time: O(2^n) where n is the length of the word
Space: O(n) recursion ... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/generate_abbreviations.py",
"license": "MIT License",
"lines": 41,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/generate_parenthesis.py | """
Generate Parentheses
Given n pairs of parentheses, generate all combinations of well-formed
parentheses.
Reference: https://leetcode.com/problems/generate-parentheses/
Complexity:
Time: O(4^n / sqrt(n)) β the n-th Catalan number
Space: O(n) recursion depth
"""
from __future__ import annotations
def g... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/generate_parenthesis.py",
"license": "MIT License",
"lines": 67,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/letter_combination.py | """
Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinations that the
number could represent using a telephone keypad mapping.
Reference: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
Complexity:
Time: O(4^n) where n is the number of digits
S... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/letter_combination.py",
"license": "MIT License",
"lines": 40,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/palindrome_partitioning.py | """
Palindrome Partitioning
Given a string, find all ways to partition it into palindromic substrings.
There is always at least one way since single characters are palindromes.
Reference: https://leetcode.com/problems/palindrome-partitioning/
Complexity:
Time: O(n * 2^n) where n is the string length
Space: ... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/palindrome_partitioning.py",
"license": "MIT License",
"lines": 49,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/pattern_match.py | """
Pattern Matching
Given a pattern and a string, determine if the string follows the same
pattern. A full match means a bijection between each letter in the pattern
and a non-empty substring in the string.
Reference: https://leetcode.com/problems/word-pattern-ii/
Complexity:
Time: O(n^m) where n is string len... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/pattern_match.py",
"license": "MIT License",
"lines": 45,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/permute.py | """
Permutations
Given a collection of distinct elements, return all possible permutations.
Reference: https://en.wikipedia.org/wiki/Permutation
Complexity:
Time: O(n * n!) where n is the number of elements
Space: O(n * n!) to store all permutations
"""
from __future__ import annotations
from collections.... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/permute.py",
"license": "MIT License",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/permute_unique.py | """
Unique Permutations
Given a collection of numbers that might contain duplicates, return all
possible unique permutations.
Reference: https://leetcode.com/problems/permutations-ii/
Complexity:
Time: O(n * n!) worst case
Space: O(n * n!) to store all unique permutations
"""
from __future__ import annotat... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/permute_unique.py",
"license": "MIT License",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/subsets.py | """
Subsets
Given a set of distinct integers, return all possible subsets (the power
set). The solution set must not contain duplicate subsets.
Reference: https://en.wikipedia.org/wiki/Power_set
Complexity:
Time: O(2^n) where n is the number of elements
Space: O(2^n) to store all subsets
"""
from __future_... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/subsets.py",
"license": "MIT License",
"lines": 53,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/backtracking/subsets_unique.py | """
Unique Subsets
Given a collection of integers that might contain duplicates, return all
possible unique subsets (the power set without duplicates).
Reference: https://leetcode.com/problems/subsets-ii/
Complexity:
Time: O(2^n) where n is the number of elements
Space: O(2^n) to store all subsets
"""
from... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/backtracking/subsets_unique.py",
"license": "MIT License",
"lines": 37,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/add_bitwise_operator.py | """
Add Bitwise Operator
Add two positive integers without using the '+' operator, using only
bitwise operations (AND, XOR, shift).
Reference: https://en.wikipedia.org/wiki/Adder_(electronics)
Complexity:
Time: O(log n) where n is the larger of the two inputs
Space: O(1)
"""
from __future__ import annotati... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/add_bitwise_operator.py",
"license": "MIT License",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/binary_gap.py | """
Binary Gap
Given a positive integer N, find and return the longest distance between two
consecutive 1-bits in the binary representation of N. If there are not two
consecutive 1-bits, return 0.
Reference: https://en.wikipedia.org/wiki/Hamming_distance
Complexity:
Time: O(log n) where n is the input integer
... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/binary_gap.py",
"license": "MIT License",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/bit_operation.py | """
Fundamental Bit Operations
Basic bit manipulation operations: get, set, clear, and update individual
bits at a specific position in an integer.
Reference: https://en.wikipedia.org/wiki/Bit_manipulation
Complexity:
Time: O(1) for all operations
Space: O(1)
"""
from __future__ import annotations
def ge... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/bit_operation.py",
"license": "MIT License",
"lines": 73,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/bytes_int_conversion.py | """
Bytes-Integer Conversion
Convert between Python integers and raw byte sequences in both big-endian
and little-endian byte orders.
Reference: https://en.wikipedia.org/wiki/Endianness
Complexity:
Time: O(b) where b is the number of bytes in the representation
Space: O(b)
"""
from __future__ import annota... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/bytes_int_conversion.py",
"license": "MIT License",
"lines": 72,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/count_flips_to_convert.py | """
Count Flips to Convert
Determine the minimal number of bits you would need to flip to convert
integer A to integer B. Uses XOR to find differing bits and Brian
Kernighan's algorithm to count them.
Reference: https://en.wikipedia.org/wiki/Hamming_distance
Complexity:
Time: O(k) where k is the number of diffe... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/count_flips_to_convert.py",
"license": "MIT License",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/count_ones.py | """
Count Ones (Hamming Weight)
Count the number of 1-bits in the binary representation of an unsigned
integer using Brian Kernighan's algorithm.
Reference: https://en.wikipedia.org/wiki/Hamming_weight
Complexity:
Time: O(k) where k is the number of set bits
Space: O(1) iterative / O(k) recursive (call stac... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/count_ones.py",
"license": "MIT License",
"lines": 42,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/find_difference.py | """
Find the Difference
Given two strings where the second is generated by shuffling the first and
adding one extra letter, find the added letter using XOR.
Reference: https://en.wikipedia.org/wiki/Exclusive_or
Complexity:
Time: O(n) where n is the length of the longer string
Space: O(1)
"""
from __future_... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/find_difference.py",
"license": "MIT License",
"lines": 27,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/find_missing_number.py | """
Find Missing Number
Given a sequence of unique integers in the range [0..n] with one value
missing, find and return that missing number. Two approaches are provided:
XOR-based and summation-based.
Reference: https://en.wikipedia.org/wiki/Exclusive_or
Complexity:
Time: O(n)
Space: O(1)
"""
from __future... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/find_missing_number.py",
"license": "MIT License",
"lines": 48,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/flip_bit_longest_sequence.py | """
Flip Bit Longest Sequence
Given an integer, find the length of the longest sequence of 1-bits you
can create by flipping exactly one 0-bit to a 1-bit.
Reference: https://en.wikipedia.org/wiki/Bit_manipulation
Complexity:
Time: O(b) where b is the number of bits in the integer
Space: O(1)
"""
from __fut... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/flip_bit_longest_sequence.py",
"license": "MIT License",
"lines": 37,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/has_alternative_bit.py | """
Has Alternating Bits
Check whether a positive integer has alternating bits, meaning no two
adjacent bits share the same value.
Reference: https://en.wikipedia.org/wiki/Bit_manipulation
Complexity:
has_alternative_bit: O(number of bits)
has_alternative_bit_fast: O(1)
"""
from __future__ import annot... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/has_alternative_bit.py",
"license": "MIT License",
"lines": 51,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/insert_bit.py | """
Insert Bit
Insert one or more bits into an integer at a specific bit position.
Reference: https://en.wikipedia.org/wiki/Bit_manipulation
Complexity:
Time: O(1)
Space: O(1)
"""
from __future__ import annotations
def insert_one_bit(number: int, bit: int, position: int) -> int:
"""Insert a single bi... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/insert_bit.py",
"license": "MIT License",
"lines": 53,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/power_of_two.py | """
Power of Two
Determine whether a given integer is a power of two using bit manipulation.
A power of two has exactly one set bit, so ``n & (n - 1)`` clears that bit
and yields zero.
Reference: https://en.wikipedia.org/wiki/Power_of_two
Complexity:
Time: O(1)
Space: O(1)
"""
from __future__ import annota... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/power_of_two.py",
"license": "MIT License",
"lines": 26,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/remove_bit.py | """
Remove Bit
Remove a single bit at a specific position from an integer, shifting
higher bits down to fill the gap.
Reference: https://en.wikipedia.org/wiki/Bit_manipulation
Complexity:
Time: O(1)
Space: O(1)
"""
from __future__ import annotations
def remove_bit(number: int, position: int) -> int:
... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/remove_bit.py",
"license": "MIT License",
"lines": 31,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/reverse_bits.py | """
Reverse Bits
Reverse the bits of a 32-bit unsigned integer.
Reference: https://en.wikipedia.org/wiki/Bit_reversal
Complexity:
Time: O(1) -- always iterates exactly 32 times
Space: O(1)
"""
from __future__ import annotations
def reverse_bits(number: int) -> int:
"""Reverse all 32 bits of an unsign... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/reverse_bits.py",
"license": "MIT License",
"lines": 26,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/single_number.py | """
Single Number
Given an array of integers where every element appears twice except for
one, find the unique element using XOR.
Reference: https://en.wikipedia.org/wiki/Exclusive_or
Complexity:
Time: O(n)
Space: O(1)
"""
from __future__ import annotations
def single_number(nums: list[int]) -> int:
... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/single_number.py",
"license": "MIT License",
"lines": 29,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/single_number2.py | """
Single Number 2
Given an array of integers where every element appears three times except
for one (which appears exactly once), find that unique element using
constant space and linear time.
Reference: https://en.wikipedia.org/wiki/Exclusive_or
Complexity:
Time: O(n)
Space: O(1)
"""
from __future__ imp... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/single_number2.py",
"license": "MIT License",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/single_number3.py | """
Single Number 3
Given an array where exactly two elements appear once and all others
appear exactly twice, find those two unique elements in O(n) time and
O(1) space.
Reference: https://en.wikipedia.org/wiki/Exclusive_or
Complexity:
Time: O(n)
Space: O(1)
"""
from __future__ import annotations
def si... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/single_number3.py",
"license": "MIT License",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
keon/algorithms:algorithms/bit_manipulation/subsets.py | """
Subsets via Bit Manipulation
Generate all possible subsets of a set of distinct integers using bitmask
enumeration. Each integer from 0 to 2^n - 1 represents a unique subset.
Reference: https://en.wikipedia.org/wiki/Power_set
Complexity:
Time: O(n * 2^n)
Space: O(n * 2^n)
"""
from __future__ import ann... | {
"repo_id": "keon/algorithms",
"file_path": "algorithms/bit_manipulation/subsets.py",
"license": "MIT License",
"lines": 31,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.