task_id stringlengths 8 8 | category stringclasses 10
values | subcategory stringclasses 39
values | is_ood_subcategory bool 1
class | difficulty stringclasses 3
values | title stringlengths 20 88 | entry_point stringlengths 8 40 | prompt stringlengths 1.18k 4.69k | canonical_solution stringlengths 330 4.19k | independent_solution stringlengths 390 8.11k | test stringlengths 761 11.6k | num_unit_tests int64 6 15 | num_adversarial_tests int64 4 18 | total_asserts int64 14 32 | distinct_outputs int64 3 27 | solution_lines int64 13 143 | generator_model stringclasses 1
value | cross_verifier_model stringclasses 1
value | split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pc-02207 | binary_search_and_greedy | Parametric binary search on answer (minimize max load, shipping capacity, bandwidth allocation) | false | hard | Minimize Maximum Load When Splitting Tasks | min_max_load | You are given a list of positive integers `tasks` where `tasks[i]` denotes the processing time of the i-th task, and an integer `k` (1 ≤ k ≤ len(tasks)) representing the number of identical machines. The tasks must be assigned to the machines **in their original order**; each machine receives a contiguous subsequence o... | def min_max_load(tasks, k):
"""Return the minimal possible maximum load when splitting `tasks` into `k`
contiguous groups.
Parameters
----------
tasks : List[int]
Positive integers representing processing times, length >= 1.
k : int
Number of groups, 1 <= k <= len(tasks).
Ret... | from typing import List
def min_max_load(tasks: List[int], k: int) -> int:
if not tasks:
return 0
n = len(tasks)
# Edge cases
if k == 1:
return sum(tasks)
if k == n:
return max(tasks)
# Binary search on the answer
low = max(tasks) # Minimum possible m... | def check(candidate):
assert candidate(*([7, 2, 5, 10, 8], 2)) == 18
assert candidate(*([1, 2, 3, 4, 5], 3)) == 6
assert candidate(*([10, 20, 30], 1)) == 60
assert candidate(*([5, 1, 9, 3], 4)) == 9
assert candidate(*([4, 4, 4, 4], 2)) == 8
assert candidate(*([1000000, 1000000, 1000000, 1000000,... | 11 | 10 | 21 | 17 | 46 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07630 | math_and_combinatorics | Modular arithmetic, prime factorization, Euler totient, and matrix exponentiation mod M | false | medium-hard | Totient Matrix Power Sum | totient_matrix_power_sum | You are to implement the function `totient_matrix_power_sum(vals: List[int], exponent: int, mod: int) -> int`.
**Function signature**
```python
def totient_matrix_power_sum(vals: List[int], exponent: int, mod: int) -> int:
```
**Parameters**
- `vals`: a list of exactly two positive integers `[x, y]` where `1 ≤ x, y ≤... | import math
from typing import List
def _phi(n: int) -> int:
"""Return Euler's totient of n using trial division up to sqrt(n)."""
if n == 1:
return 1
result = n
x = n
p = 2
while p * p <= x:
if x % p == 0:
while x % p == 0:
x //= p
result... | def totient_matrix_power_sum(vals: list, exponent: int, mod: int) -> int:
def phi(n: int) -> int:
if n == 1:
return 1
result = n
p = 2
temp = n
while p * p <= temp:
if temp % p == 0:
while temp % p == 0:
temp //= p
... | def check(candidate):
assert candidate(*([2, 3], 0, 100)) == 2
assert candidate(*([5, 7], 1, 1000)) == 20
assert candidate(*([10, 13], 2, 123456789)) == 512
assert candidate(*([1, 1000003], 3, 1000000007)) == 53874152
assert candidate(*([12, 12], 5, 999983)) == 65536
assert candidate(*([10000000... | 10 | 12 | 22 | 13 | 48 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04161 | dynamic_programming | Knapsack variants (bounded, subset partitioning, minimum coin/item combination with tie-break) | false | medium | Minimum Item Count for Exact Weight with Lexicographic Tie‑Break | min_items_knapsack | Write a function `min_items_knapsack(weights: List[int], target: int) -> List[int]` that selects a subset of the given items whose total weight is exactly `target`.
* Each element of `weights` is a positive integer (1 ≤ weight ≤ 10^4). The list length `n` satisfies 0 ≤ n ≤ 30.
* `target` is a non‑negative integer (0 ≤... | def min_items_knapsack(weights, target):
n = len(weights)
# dp[sum] = (count, tuple_of_indices)
# initialize with impossible sentinel
from math import inf
dp = {0: (0, ())}
for idx, w in enumerate(weights):
# iterate over a snapshot of current keys to avoid reuse of the same item
... | from typing import List
def min_items_knapsack(weights: List[int], target: int) -> List[int]:
n = len(weights)
# Edge case: target is 0
if target == 0:
return []
# Edge case: no items
if n == 0:
return []
# dp[w] = (min_items, best_indices) to achieve weight w
... | def check(candidate):
assert candidate(*([3, 1, 4, 2, 5], 7)) == [0, 2]
assert candidate(*([2, 2, 2], 3)) == []
assert candidate(*([1, 2, 3, 4], 5)) == [0, 3]
assert candidate(*([], 0)) == []
assert candidate(*([], 10)) == []
assert candidate(*([5, 7, 2], 14)) == [0, 1, 2]
assert candidate(*... | 13 | 9 | 22 | 12 | 28 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02541 | state_machines_and_systems | Vector-clock / Lamport timestamp causality comparator and concurrent event detector | false | medium | Vector Clock Causality Comparator | compare_vector_clocks | You are given two vector clocks, each represented as a JSON object (Python dict) that maps a process identifier (string) to a non‑negative integer timestamp. A vector clock may omit some process identifiers; any omitted identifier is implicitly mapped to timestamp 0.
Implement the function
def compare_vector_cloc... | def compare_vector_clocks(vc1, vc2):
"""Compare two vector clocks.
Returns -1 if vc1 happened before vc2, 1 if after, 0 if concurrent or equal.
The inputs are not mutated.
"""
# Collect all process identifiers appearing in either clock
keys = set(vc1.keys()) | set(vc2.keys())
less = False ... | def compare_vector_clocks(vc1: dict, vc2: dict) -> int:
# Collect all process identifiers from both vector clocks
all_processes = set(vc1.keys()) | set(vc2.keys())
vc1_less = False
vc2_less = False
for p in all_processes:
t1 = vc1.get(p, 0)
t2 = vc2.get(p, 0)
... | def check(candidate):
assert candidate(*({'A': 0}, {'A': 0})) == 0
assert candidate(*({'A': 1}, {'A': 2})) == -1
assert candidate(*({'A': 5, 'B': 3}, {'A': 5, 'B': 2})) == 1
assert candidate(*({'A': 2, 'B': 1}, {'A': 3, 'B': 1})) == -1
assert candidate(*({'X': 4}, {'X': 4, 'Y': 1})) == -1
assert... | 13 | 11 | 24 | 3 | 25 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02286 | strings_and_text_processing | Custom tokenization, run-length / LZ-style lossless compression and decompression | false | medium | Custom tokenization with run‑length and back‑reference compression | compress_text | You are given a single argument `s` (type `str`). Implement the function `compress_text(s: str) -> str` that returns a deterministic loss‑less compression of the input string using two kinds of tokens, applied greedily from left to right.
**Tokens**
1. **Run‑length token** – a maximal consecutive run of the same chara... | def compress_text(s: str) -> str:
"""Compress `s` using run‑length and back‑reference tokens as described.
The algorithm scans left‑to‑right, at each position selecting the longest
possible back‑reference (length >= 2) with the smallest start index on ties.
If none exists, it emits a run‑length token.
... | def compress_text(s: str) -> str:
if not s:
return ""
n = len(s)
result = []
pos = 0
while pos < n:
# Try to find the longest back-reference starting at pos
# The back-reference must point to a substring that first appeared at some start index
# and the refe... | def check(candidate):
assert candidate(*('',)) == ''
assert candidate(*('a',)) == 'a'
assert candidate(*('aa',)) == 'a2'
assert candidate(*('ababa',)) == 'ab@0:2a'
assert candidate(*('abcabcabc',)) == 'abc@0:3@0:3'
assert candidate(*('aaaaa',)) == 'a5'
assert candidate(*('abcaabca',)) == 'ab... | 14 | 8 | 22 | 22 | 46 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05703 | dynamic_programming | Interval scheduling, weighted job partitioning, and non-overlapping segment optimization | false | medium | Maximum total weight of non‑overlapping jobs | max_weight_non_overlapping | You are given a list of jobs, each represented as a three‑element list ``[start, end, weight]`` where ``start`` and ``end`` are non‑negative integers with ``start < end`` and ``weight`` is a positive integer. A job occupies the half‑open time interval ``[start, end)``; two jobs overlap if their intervals intersect (i.e... | from bisect import bisect_right
from typing import List
def max_weight_non_overlapping(jobs: List[List[int]]) -> int:
"""Return the maximum total weight of a set of non‑overlapping jobs.
Each job is [start, end, weight] with start < end.
"""
if not jobs:
return 0
# Sort jobs by end time
... | def max_weight_non_overlapping(jobs):
if not jobs:
return 0
# Sort jobs by end time
sorted_jobs = sorted(jobs, key=lambda x: x[1])
n = len(sorted_jobs)
# dp[i] = max weight using subset of first i jobs (1-indexed)
# We'll use a list where dp[i] corresponds to considering j... | def check(candidate):
assert candidate(*([],)) == 0
assert candidate(*([[0, 1, 10]],)) == 10
assert candidate(*([[0, 2, 5], [2, 4, 7]],)) == 12
assert candidate(*([[0, 3, 4], [1, 4, 9]],)) == 9
assert candidate(*([[1, 3, 5], [2, 5, 6], [4, 6, 5]],)) == 10
assert candidate(*([[0, 3, 4], [1, 3, 5]... | 14 | 10 | 24 | 14 | 24 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03022 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | medium-hard | Lexicographically Smallest Topological Order and Critical Path in a Weighted DAG | dag_schedule_and_critical_path | You are to implement a function with the exact signature:
```python
def dag_schedule_and_critical_path(num_tasks: int, edges: List[List[int]], durations: List[int]) -> Dict[str, Any]:
```
**Parameters**
- `num_tasks`: the number of tasks (vertices) in the directed graph, labeled `0` through `num_tasks-1`. `1 ≤ num_ta... | import heapq
from typing import List, Dict, Any
def dag_schedule_and_critical_path(num_tasks: int, edges: List[List[int]], durations: List[int]) -> Dict[str, Any]:
# Edge cases
if num_tasks == 0:
return {"order": [], "critical_path": 0}
# Build adjacency list and indegree array
adj = [[] for _ ... | import heapq
from typing import List, Dict, Any
def dag_schedule_and_critical_path(num_tasks: int, edges: List[List[int]], durations: List[int]) -> Dict[str, Any]:
if num_tasks == 0:
return {"order": [], "critical_path": 0}
# Build adjacency list and compute in-degrees
adj = [[] for _ in range... | def check(candidate):
assert candidate(*(1, [], [7])) == {'order': [0], 'critical_path': 7}
assert candidate(*(4, [], [1, 2, 3, 4])) == {'order': [0, 1, 2, 3], 'critical_path': 4}
assert candidate(*(3, [[0, 1], [1, 2]], [5, 5, 5])) == {'order': [0, 1, 2], 'critical_path': 15}
assert candidate(*(4, [[0, ... | 12 | 11 | 23 | 20 | 38 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06529 | business_logic_and_fintech | Progressive tax bracket & tiered fee calculator with exact integer-cent rounding | false | medium-hard | Progressive Tax and Tiered Fee Calculator with Cent Precision | compute_total_payment_cents | You are to implement a function `compute_total_payment_cents(income_cents: int, tax_brackets: List[Tuple[int, int, int]], fee_tiers: List[Tuple[int, int]]) -> int`.
**Parameters**
- `income_cents`: a non‑negative integer representing the gross income in **cents** (i.e., 1 dollar = 100 cents). 0 ≤ `income_cents` ≤ 10^1... | def compute_total_payment_cents(income_cents, tax_brackets, fee_tiers):
# Compute total tax using per‑bracket half‑up rounding
remaining = income_cents
total_tax = 0
for lower, upper, rate in tax_brackets:
if remaining <= 0:
break
# Determine taxable portion in this bracket
... | def compute_total_payment_cents(income_cents: int, tax_brackets: list, fee_tiers: list) -> int:
if income_cents == 0:
return 0
# Calculate total tax
total_tax_cents = 0
remaining_income = income_cents
for lower, upper, rate in tax_brackets:
if remaining_income <= 0:
... | def check(candidate):
assert candidate(*(0, [(0, 1000000, 1000)], [])) == 0
assert candidate(*(50000, [(0, 1000000, 1500)], [(60000, 2000)])) == 42500
assert candidate(*(123456, [(0, 100000, 1000), (100000, 200000, 2000)], [(100000, 5000), (120000, 8000)])) == 113765
assert candidate(*(250000, [(0, 1000... | 10 | 11 | 21 | 17 | 27 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07413 | dynamic_programming | Knapsack variants (bounded, subset partitioning, minimum coin/item combination with tie-break) | false | medium | Minimum Weight Subset for Exact Value with Tie‑Breakers | min_weight_subset | You are given a list of items and a target integer value. Each item is represented by a dictionary with two keys:
* "weight" – a positive integer weight of the item.
* "value" – a positive integer value contributed by the item.
```python
items: List[Dict[str, int]]
target: int
```
Your task is to select a **subset*... | def min_weight_subset(items, target):
from typing import List, Dict, Optional, Any
n = len(items)
# dp[v] = (total_weight, item_count, indices_tuple) for best subset achieving value v
# Initialize with None (unreachable)
dp: List[Optional[tuple]] = [None] * (target + 1)
dp[0] = (0, 0, ()) # zer... | from typing import List, Dict, Any, Optional
import copy
def min_weight_subset(items: List[Dict[str, int]], target: int) -> Optional[Dict[str, Any]]:
n = len(items)
if target == 0:
return {"total_weight": 0, "indices": []}
if n == 0:
return None
# dp[v] = (min_weight, min_count, be... | def check(candidate):
assert candidate(*([{'weight': 5, 'value': 10}], 10)) == {'total_weight': 5, 'indices': [0]}
assert candidate(*([{'weight': 3, 'value': 4}, {'weight': 2, 'value': 4}, {'weight': 5, 'value': 6}], 8)) == {'total_weight': 5, 'indices': [0, 1]}
assert candidate(*([{'weight': 1, 'value': 3}... | 10 | 12 | 22 | 16 | 37 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02401 | state_machines_and_systems | Memory allocator simulator (first-fit / best-fit free list with adjacent block coalescing) | false | medium-hard | First‑Fit / Best‑Fit Memory Allocator Simulator with Coalescing | memory_allocator | You are to implement a deterministic memory allocator simulator.
**Function signature**
```python
def memory_allocator(total_size: int, operations: List[Tuple[str, int]]) -> List[int]:
```
* `total_size` – positive integer (1 ≤ total_size ≤ 10⁹) representing the size of a contiguous memory region whose addresses start... | import bisect
from typing import List, Tuple
def memory_allocator(total_size: int, operations: List[Tuple[str, int]]) -> List[int]:
# free list as list of [start, end) intervals, always sorted, non‑overlapping
free = [[0, total_size]]
# allocated blocks: start -> size
allocated = {}
results: List[i... | from typing import List, Tuple
def memory_allocator(total_size: int, operations: List[Tuple[str, int]]) -> List[int]:
# Free list: list of [start, end) intervals, sorted by start address
free_list = [[0, total_size]]
# Allocated blocks: dict mapping start_address -> end_address
allocated = {}
... | def check(candidate):
assert candidate(*(5, [('alloc', 5)])) == [0]
assert candidate(*(4, [('alloc', 5)])) == [-1]
assert candidate(*(10, [('free', 0)])) == [-1]
assert candidate(*(10, [('alloc', 3), ('alloc', 4), ('free', 0), ('alloc', 5)])) == [0, 3, 0, -1]
assert candidate(*(20, [('alloc', 5), ('... | 14 | 11 | 25 | 19 | 52 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02312 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | hard | Lexicographically Smallest Topological Order and Critical Path Duration | schedule_tasks | You are given a directed acyclic graph (DAG) that represents a set of tasks and their precedence constraints.
**Function signature**
```python
def schedule_tasks(tasks: dict[str, int], edges: list[list[str]]) -> tuple[list[str], int]:
```
- `tasks` maps each task name (a non‑empty string consisting of lower‑case Engli... | import heapq
from collections import defaultdict, deque
def schedule_tasks(tasks, edges):
# Build graph and compute in‑degrees
graph = defaultdict(list)
indeg = {node: 0 for node in tasks}
seen_edges = set()
for pre, post in edges:
if (pre, post) in seen_edges:
continue
... | import heapq
from collections import defaultdict, deque
def schedule_tasks(tasks: dict[str, int], edges: list[list[str]]) -> tuple[list[str], int]:
# Build adjacency list and in-degree count
# Use a set for edges to handle duplicates
adj = defaultdict(list)
in_degree = defaultdict(int)
# Initi... | def check(candidate):
assert candidate(*({'a': 5}, [])) == (['a'], 5)
assert candidate(*({'b': 2, 'a': 3}, [])) == (['a', 'b'], 3)
assert candidate(*({'a': 1, 'b': 2, 'c': 3}, [['a', 'c'], ['b', 'c']])) == (['a', 'b', 'c'], 5)
assert candidate(*({'x': 4, 'y': 5, 'z': 6}, [['x', 'y'], ['y', 'z']])) == ([... | 10 | 10 | 20 | 17 | 40 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06480 | math_and_combinatorics | Modular arithmetic, prime factorization, Euler totient, and matrix exponentiation mod M | false | medium | Sum of Totient-GCD Matrix Powers | sum_totient_gcd_matrix_power | You are to implement the function
```python
def sum_totient_gcd_matrix_power(N: int, K: int, M: int) -> int:
```
where:
- **N** (1 ≤ N ≤ 30) is the size of a square matrix.
- **K** (0 ≤ K ≤ 10^9) is the exponent.
- **M** (2 ≤ M ≤ 10^9+7) is a positive modulus (not necessarily prime).
First compute the Euler totient φ(... | import math
def _compute_totients(n: int) -> list:
phi = list(range(n + 1))
for i in range(2, n + 1):
if phi[i] == i: # i is prime
for j in range(i, n + 1, i):
phi[j] -= phi[j] // i
return phi[1:]
def _matrix_mul(a, b, mod):
n = len(a)
res = [[0] * n for _ in r... | def sum_totient_gcd_matrix_power(N: int, K: int, M: int) -> int:
# Compute Euler totient for 1..N
def compute_totients(n):
phi = list(range(n + 1))
for i in range(2, n + 1):
if phi[i] == i: # i is prime
for j in range(i, n + 1, i):
phi[j] -= phi[j... | def check(candidate):
assert candidate(*(1, 0, 5)) == 1
assert candidate(*(1, 10, 100)) == 1
assert candidate(*(2, 0, 1000)) == 2
assert candidate(*(2, 1, 1000)) == 4
assert candidate(*(2, 2, 1000)) == 8
assert candidate(*(3, 1, 50)) == 10
assert candidate(*(3, 2, 100)) == 34
assert cand... | 12 | 9 | 21 | 14 | 51 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03900 | math_and_combinatorics | Exact rational arithmetic using integer pairs, continued fractions, and linear Diophantine checks | false | medium | Exact Rational Continued Fraction and Coprime Linear Check | solve_fraction_tasks | Write a function `solve_fraction_tasks(frac: List[int], coeffs: List[int]) -> Dict[str, Any]`.
**Parameters**
- `frac`: a list of two integers `[p, q]` representing the rational number `p/q`. It is guaranteed that `q > 0` and `gcd(p, q) = 1` (the fraction is already in lowest terms). `p` may be zero or negative.
- `co... | def solve_fraction_tasks(frac, coeffs):
from math import floor
from typing import List, Dict, Any
p, q = frac[0], frac[1]
# Continued fraction
if p == 0:
cf = [0]
else:
cf = []
while q != 0:
a = floor(p / q) # works for negative numbers as well
cf... | from math import gcd
from typing import List, Dict, Any
def solve_fraction_tasks(frac: List[int], coeffs: List[int]) -> Dict[str, Any]:
# Extract p and q from frac
p, q = frac[0], frac[1]
# Compute continued fraction expansion
# Edge case: if p is 0, the continued fraction is [0]
if p == 0:
... | def check(candidate):
assert candidate(*([4, 3], [6, 9])) == {'continued_fraction': [1, 3], 'has_solution': False}
assert candidate(*([-7, 5], [14, -13])) == {'continued_fraction': [-2, 1, 1, 2], 'has_solution': True}
assert candidate(*([0, 5], [0, 0])) == {'continued_fraction': [0], 'has_solution': False}
... | 14 | 10 | 24 | 23 | 21 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-01923 | dynamic_programming | Knapsack variants (bounded, subset partitioning, minimum coin/item combination with tie-break) | false | medium | Minimum Value Knapsack with Tie‑Breakers | min_value_knapsack | Write a function `min_value_knapsack(items: List[Tuple[int, int]], target: int) -> List[int]`.
* `items` is a list of *n* tuples `(weight, value)`. Both weight and value are positive integers (≥ 1). The list is 0‑indexed; the index of a tuple is its identifier.
* `target` is a non‑negative integer representing the min... | def min_value_knapsack(items, target):
from itertools import combinations
n = len(items)
best = None # tuple (total_value, item_count, indices_tuple)
# Enumerate all subsets using bitmask (n ≤ 30, 2^30 ~ 1e9 too large). Use DP on weight.
# We will use a dictionary mapping weight -> (value, count, i... | from typing import List, Tuple
def min_value_knapsack(items: List[Tuple[int, int]], target: int) -> List[int]:
n = len(items)
if target == 0:
return []
if n == 0:
return []
# We need to find a subset with weight >= target, minimizing value, then size, then lexicographic order of in... | def check(candidate):
assert candidate(*([(3, 4), (5, 6), (2, 2)], 7)) == [1, 2]
assert candidate(*([(4, 5), (4, 5), (4, 5)], 8)) == [0, 1]
assert candidate(*([(1, 2), (2, 3)], 10)) == []
assert candidate(*([], 0)) == []
assert candidate(*([], 5)) == []
assert candidate(*([(10, 1)], 5)) == [0]
... | 12 | 8 | 20 | 9 | 36 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04273 | dynamic_programming | Knapsack variants (bounded, subset partitioning, minimum coin/item combination with tie-break) | false | medium-hard | Minimum Items for Exact Weight with Lexicographic Tie‑Break | min_items_with_tie | You are given a list `weights` of **distinct** positive integers and a positive integer `target`. Each weight may be used **at most once** (0‑1 knapsack). Return a list of **0‑based indices** of a subset of `weights` whose sum is exactly `target` and whose size (number of chosen items) is **minimum** among all such s... | from typing import List, Tuple
def min_items_with_tie(weights: List[int], target: int) -> List[int]:
n = len(weights)
# dp[s] = (cnt, path) where cnt is minimal number of items to reach sum s,
# and path is the sorted tuple of indices achieving that count with lexicographically smallest order.
# Initia... | from typing import List
def min_items_with_tie(weights: List[int], target: int) -> List[int]:
n = len(weights)
# dp[s] = (min_items, best_indices_tuple) for sum s
# We want to minimize number of items, then lexicographically smallest sorted index list.
# Since we need lexicographically smallest sorted ... | def check(candidate):
assert candidate(*([4, 2, 7, 1, 3], 6)) == [0, 1]
assert candidate(*([5, 1, 2, 3], 6)) == [0, 1]
assert candidate(*([8, 9, 10], 5)) == []
assert candidate(*([7, 2, 5], 7)) == [0]
assert candidate(*([1, 2, 3], 0)) == []
assert candidate(*([6, 4, 3, 2, 9, 1], 7)) == [0, 5]
... | 12 | 12 | 24 | 13 | 25 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07797 | binary_search_and_greedy | Two-pointer / prefix-sum subarray bounds with negative numbers and modular constraints | false | medium | Count subarrays with modular sum under negative numbers | count_modular_subarrays | You are given a list of integers `nums` (which may contain negative numbers), and two positive integers `k` and `m` such that `0 <= m < k`. A *subarray* is any contiguous slice `nums[l..r]` (0‑based, inclusive). Define the *modular sum* of a subarray as `(sum_{i=l}^{r} nums[i]) mod k`, where the modulo operation always... | def count_modular_subarrays(nums, k, m):
"""Return the number of subarrays whose sum modulo k equals m.
Args:
nums (List[int]): list of integers, may contain negatives.
k (int): positive modulus.
m (int): target modulo, 0 <= m < k.
Returns:
int: count of qualifying subarrays... | from typing import List
from collections import defaultdict
def count_modular_subarrays(nums: List[int], k: int, m: int) -> int:
if not nums:
return 0
# We use prefix sums modulo k.
# Let prefix[i] = (nums[0] + ... + nums[i-1]) % k, with prefix[0] = 0.
# A subarray nums[l..r] has sum S = p... | def check(candidate):
assert candidate(*([3, -1, 4, -2, 2], 5, 3)) == 4
assert candidate(*([0, 0, 0], 7, 0)) == 6
assert candidate(*([5], 10, 5)) == 1
assert candidate(*([5], 10, 3)) == 0
assert candidate(*([-2, -3, -5], 4, 0)) == 1
assert candidate(*([1000000000, -1000000000, 1], 1000000000, 1)... | 12 | 10 | 22 | 8 | 25 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07946 | strings_and_text_processing | Fuzzy string search, k-mismatch pattern finder, and palindrome partitioning | false | hard | Fuzzy Pattern Search with K‑Mismatches and Palindrome Partition Tie‑Breaker | select_fuzzy_pattern | You are to implement the function `select_fuzzy_pattern(text: str, patterns: List[str], k: int) -> Tuple[Optional[str], int, int, int]`.
**Definitions**
- *Hamming distance* between two equal‑length strings is the number of positions at which the corresponding characters differ.
- *Minimum palindrome partition cuts* o... | def select_fuzzy_pattern(text, patterns, k):
"""Return the best pattern according to the specification.
Parameters
----------
text: str
The source string.
patterns: List[str]
List of candidate patterns.
k: int
Maximum allowed Hamming distance.
Returns
-------
... | from typing import List, Optional, Tuple
def select_fuzzy_pattern(text: str, patterns: List[str], k: int) -> Tuple[Optional[str], int, int, int]:
"""
Select the best fuzzy pattern match from a list of patterns in a given text.
Args:
text: The text to search in.
patterns: List of patter... | def check(candidate):
assert candidate(*('abacaba', ['aba', 'caa', 'bac'], 1)) == ('aba', 0, 0, 0)
assert candidate(*('aaaaa', ['ab', 'ba', 'aa'], 1)) == ('aa', 0, 0, 0)
assert candidate(*('xyz', ['abc', 'def'], 2)) == (None, -1, -1, -1)
assert candidate(*('abcde', ['abcde'], 0)) == ('abcde', 0, 0, 4)
... | 14 | 12 | 26 | 18 | 89 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04167 | binary_search_and_greedy | Two-pointer / prefix-sum subarray bounds with negative numbers and modular constraints | false | medium | Count subarrays with given modular sum | count_subarrays_modulo | You are given a list of integers `nums` (which may contain negative numbers), an integer divisor `k` (k > 0), and a target remainder `m` (0 <= m < k). A *subarray* is any contiguous slice of `nums` with length at least 1.
Your task is to implement the function
```python
def count_subarrays_modulo(nums: List[int], k: ... | import itertools
from typing import List
def count_subarrays_modulo(nums: List[int], k: int, m: int) -> int:
# Edge case for out‑of‑spec empty input
if not nums:
return 0
# prefix_mod holds (prefix sum % k) for each prefix ending before index i
# Start with prefix sum 0 at position -1
prefi... | from typing import List
from collections import defaultdict
def count_subarrays_modulo(nums: List[int], k: int, m: int) -> int:
if not nums:
return 0
# We need to count pairs (i, j) with i <= j such that
# (prefix_sum[j+1] - prefix_sum[i]) % k == m
# This is equivalent to:
# prefix_sum... | def check(candidate):
assert candidate(*([3, 1, 4, 1, 5], 5, 0)) == 4
assert candidate(*([-2, 2, -3, 3], 4, 1)) == 2
assert candidate(*([7], 5, 2)) == 1
assert candidate(*([7], 5, 3)) == 0
assert candidate(*([0, 0, 0], 3, 0)) == 6
assert candidate(*([0, 0, 0], 3, 1)) == 0
assert candidate(*(... | 11 | 12 | 23 | 9 | 21 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05889 | business_logic_and_fintech | Prorated SaaS subscription billing, mid-cycle tier upgrades, and exact integer-cent ledger | false | medium | Prorated SaaS Upgrade Charge Calculator | calculate_prorated_charge | You are to implement a function `calculate_prorated_charge(current_plan, upgrade_plan, days_used, days_in_cycle)` that computes the net amount (in integer cents) that must be charged to a customer when they upgrade their subscription tier in the middle of a billing cycle.
**Function signature**
```python
def calculate... | def calculate_prorated_charge(current_plan, upgrade_plan, days_used, days_in_cycle):
# Extract prices (they are guaranteed to exist and be non‑negative ints)
current_price = current_plan['price_cents']
upgrade_price = upgrade_plan['price_cents']
# Compute unused days
unused_days = days_in_cycle - d... | def calculate_prorated_charge(current_plan: dict, upgrade_plan: dict, days_used: int, days_in_cycle: int) -> int:
# Extract prices without modifying inputs
current_price = current_plan['price_cents']
upgrade_price = upgrade_plan['price_cents']
# Calculate unused days
unused_days = days_in_cycle... | def check(candidate):
assert candidate(*({'price_cents': 3000}, {'price_cents': 5000}, 10, 30)) == 1333
assert candidate(*({'price_cents': 2500}, {'price_cents': 2500}, 15, 30)) == 0
assert candidate(*({'price_cents': 1000}, {'price_cents': 2000}, 0, 30)) == 1000
assert candidate(*({'price_cents': 4000}... | 12 | 10 | 22 | 14 | 15 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02630 | math_and_combinatorics | 2D integer computational geometry (convex hull, doubled polygon area, segment intersection) | false | hard | Interior lattice points of the convex hull | count_interior_lattice_points | Write a function `count_interior_lattice_points(points: List[List[int]]) -> int` that receives a list of 2‑dimensional integer points and returns the number of lattice points (points with integer coordinates) that lie strictly inside the convex hull of the given set.
**Definitions & Rules**
- A *lattice point* is any ... | import math
from typing import List
def _cross(o, a, b):
return (a[0]-o[0])*(b[1]-o[1]) - (a[1]-o[1])*(b[0]-o[0])
def _convex_hull(points: List[List[int]]) -> List[List[int]]:
# Monotone chain, returns vertices in CCW order without duplicate last point
pts = sorted(set(map(tuple, points)))
if len(pts)... | import math
from typing import List
def count_interior_lattice_points(points: List[List[int]]) -> int:
"""
Count the number of interior lattice points in the convex hull of the given points.
Uses Pick's theorem: I = (2*Area - B + 2) // 2
"""
if len(points) < 3:
return 0
# Remove du... | def check(candidate):
assert candidate(*([[0, 0]],)) == 0
assert candidate(*([[0, 0], [1, 1]],)) == 0
assert candidate(*([[0, 0], [2, 0], [0, 2]],)) == 0
assert candidate(*([[0, 0], [4, 0], [4, 3], [0, 3]],)) == 6
assert candidate(*([[0, 0], [2, 0], [2, 2], [0, 2]],)) == 1
assert candidate(*([[0... | 13 | 6 | 19 | 12 | 48 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03227 | binary_search_and_greedy | Two-pointer / prefix-sum subarray bounds with negative numbers and modular constraints | false | hard | Longest Subarray with Given Modulo | longest_modular_subarray | You are to implement the function `longest_modular_subarray(arr: List[int], k: int, m: int) -> Tuple[int, int]`.
**Problem statement**
Given an integer array `arr` (which may contain negative numbers), an integer `k` and a positive integer `m`, find a contiguous sub‑array (i.e., a slice `arr[l..r]` with `0 <= l <= r <... | from typing import List, Tuple
def longest_modular_subarray(arr: List[int], k: int, m: int) -> Tuple[int, int]:
# prefix sum modulo m
n = len(arr)
pref_mod = 0
# earliest index where a particular remainder occurs
earliest = {0: 0} # pref[0] = 0 at index 0
best_len = 0
best_start = -1
f... | from typing import List, Tuple
def longest_modular_subarray(arr: List[int], k: int, m: int) -> Tuple[int, int]:
n = len(arr)
if n == 0:
return (0, -1)
# We need to find the longest subarray arr[l..r] such that
# (prefix[r+1] - prefix[l]) % m == k
# which means prefix[l] % m == (prefix[... | def check(candidate):
assert candidate(*([3, 1, 4, 1, 5], 2, 6)) == (5, 0)
assert candidate(*([-2, 2, -3, 3, 1], 0, 5)) == (4, 0)
assert candidate(*([1, 2, 3], 4, 5)) == (0, -1)
assert candidate(*([5, 5, 5], 0, 5)) == (3, 0)
assert candidate(*([1, 2, 3, 4, 5], 3, 6)) == (5, 0)
assert candidate(*... | 12 | 12 | 24 | 9 | 26 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07079 | business_logic_and_fintech | Prorated SaaS subscription billing, mid-cycle tier upgrades, and exact integer-cent ledger | false | hard | Prorated SaaS Subscription Billing with Mid‑Cycle Tier Upgrades | compute_total_charge | You are implementing the core billing logic for a SaaS product that offers three subscription tiers:\n\n* **Tier 0** – Free, price $0 per month.\n* **Tier 1** – Basic, price $10 per month.\n* **Tier 2** – Pro, price $25 per month.\n\nAll prices are expressed in **cents** (i.e. 1000 means $10.00).\n\nA customer can ch... | def compute_total_charge(events):
# Validate input
if not isinstance(events, list):
raise ValueError('events must be a list')
prev_day = 0
for ev in events:
if not (isinstance(ev, tuple) and len(ev) == 2):
raise ValueError('each event must be a (day, tier) tuple')
day... | def compute_total_charge(events: list) -> int:
# Validate input
if not isinstance(events, list):
raise ValueError("Events must be a list")
# Check for empty list
if len(events) == 0:
return 0
# Validate each event
for event in events:
if not isinstance(event, tu... | def check(candidate):
assert candidate(*([],)) == 0
assert candidate(*([(1, 1)],)) == 1000
assert candidate(*([(30, 2)],)) == 83
assert candidate(*([(6, 2), (16, 1)],)) == 1333
assert candidate(*([(10, 1), (20, 0)],)) == 333
assert candidate(*([(5, 1), (15, 2), (25, 0)],)) == 1166
assert can... | 10 | 5 | 15 | 13 | 41 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03987 | binary_search_and_greedy | Parametric binary search on answer (minimize max load, shipping capacity, bandwidth allocation) | false | medium | Minimize Maximum Load When Splitting Jobs Among Machines | min_max_load | You are given a list of positive integers `jobs` where `jobs[i]` represents the amount of work of the i‑th job, and an integer `k` (1 ≤ k ≤ len(jobs)) representing the number of identical machines available. Each machine must process a **contiguous** segment of the job list (the order of jobs cannot be changed). Every ... | import bisect
from typing import List
def min_max_load(jobs: List[int], k: int) -> int:
# Helper: can we split into <=k groups with each group sum <= limit?
def feasible(limit: int) -> bool:
groups = 1
current = 0
for w in jobs:
if w > limit:
return False
... | from typing import List
def min_max_load(jobs: List[int], k: int) -> int:
if not jobs:
return 0
n = len(jobs)
# If k >= n, each job can be its own group, so answer is max(jobs)
if k >= n:
return max(jobs)
# Binary search on the answer M
# Lower bound: max(jobs) be... | def check(candidate):
assert candidate(*([7, 2, 5, 10, 8], 2)) == 18
assert candidate(*([1, 2, 3, 4, 5], 3)) == 6
assert candidate(*([5, 1, 9, 3], 4)) == 9
assert candidate(*([4, 4, 4, 4], 1)) == 16
assert candidate(*([2, 2, 2, 2, 2, 2], 3)) == 4
assert candidate(*([100, 1, 1, 1, 1], 3)) == 100
... | 14 | 11 | 25 | 19 | 31 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07133 | dynamic_programming | 2D grid DP with obstacles, energy/budget constraints, and exact minimum cost | false | hard | Minimum-cost path in a grid with obstacles and penalty | min_cost_path | You are given a rectangular grid `grid` of size `m × n` (1 ≤ m, n ≤ 50). Each cell `grid[i][j]` is either a non‑negative integer cost (0 ≤ cost ≤ 10^4) indicating the amount of energy required to step onto that cell, or the integer `-1` indicating an impassable obstacle.
You start in the top‑left cell `(0, 0)` and mus... | import heapq
from typing import List
def min_cost_path(grid: List[List[int]], penalty: int, energy: int) -> int:
m = len(grid)
n = len(grid[0]) if m else 0
if m == 0 or n == 0:
return -1
# helper to compute cost of entering a cell
def cell_cost(i: int, j: int) -> int:
return penalty... | from typing import List
import heapq
def min_cost_path(grid: List[List[int]], penalty: int, energy: int) -> int:
m = len(grid)
n = len(grid[0])
# If start or end is out of bounds (shouldn't happen per constraints), handle gracefully
if m == 0 or n == 0:
return -1
# Calculate cost ... | def check(candidate):
assert candidate(*([[0]], 0, 1)) == 0
assert candidate(*([[-1]], 5, 5)) == 5
assert candidate(*([[-1, 2], [3, 4]], 3, 15)) == 9
assert candidate(*([[1, 2], [3, 4]], 0, 5)) == -1
assert candidate(*([[1, 1, 1], [1, -1, 1], [1, 1, 1]], 2, 10)) == 5
assert candidate(*([[1, -1, ... | 11 | 10 | 21 | 10 | 34 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-09137 | business_logic_and_fintech | Prorated SaaS subscription billing, mid-cycle tier upgrades, and exact integer-cent ledger | false | hard | Prorated SaaS Subscription Billing with Mid‑Cycle Tier Upgrades | calculate_total_cents | You are given the billing history of a single SaaS customer.
Each subscription period is represented by a dictionary with the following keys:
* `"start"` – inclusive start day of the period, integer ≥ 1.
* `"end"` – inclusive end day of the period, integer ≥ `start`.
* `"daily_rate"` – cost per day for the tier that... | from typing import List, Dict
def calculate_total_cents(subscriptions: List[Dict[str, int]], upgrades: List[Dict[str, int]]) -> int:
if not subscriptions:
return 0
# Build a map day -> rate after applying upgrades
# First, create a list of (day, rate) for the original periods
# We'll walk throu... | from typing import List, Dict
def calculate_total_cents(subscriptions: List[Dict[str, int]], upgrades: List[Dict[str, int]]) -> int:
if not subscriptions:
return 0
# Find the global start and end days
global_start = min(s['start'] for s in subscriptions)
global_end = max(s['end'] for s in ... | def check(candidate):
assert candidate(*([{'start': 1, 'end': 1, 'daily_rate': 50}], [])) == 50
assert candidate(*([{'start': 1, 'end': 10, 'daily_rate': 100}], [{'day': 5, 'new_daily_rate': 150}])) == 1300
assert candidate(*([{'start': 1, 'end': 30, 'daily_rate': 200}, {'start': 31, 'end': 60, 'daily_rate'... | 11 | 12 | 23 | 19 | 27 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-09719 | state_machines_and_systems | Vector-clock / Lamport timestamp causality comparator and concurrent event detector | false | hard | Vector Clock Concurrent Pair Detector | find_concurrent_pairs | You are given a list `clocks` of length *n* (1 ≤ n ≤ 2000). Each element is a dictionary representing a vector clock of a single event in a distributed system. Keys are process identifiers (non‑empty strings containing only ASCII letters and digits) and values are non‑negative integers (0 ≤ value ≤ 10⁹). A process may ... | from typing import List, Dict
def _compare(a: Dict[str, int], b: Dict[str, int]) -> int:
"""Return -1 if a happens-before b, 1 if a happens-after b, 0 if concurrent.
Missing keys are treated as 0.
"""
less = False
greater = False
# iterate over union of keys
keys = set(a.keys()) | set(b.key... | from typing import List, Dict
def find_concurrent_pairs(clocks: List[Dict[str, int]]) -> List[List[int]]:
n = len(clocks)
if n < 2:
return []
# Collect all process identifiers to build a complete mapping
all_processes = set()
for clock in clocks:
all_processes.update(clock.keys... | def check(candidate):
assert candidate(*([],)) == []
assert candidate(*([{'A': 1, 'B': 0}],)) == []
assert candidate(*([{'p': 2}, {'p': 2}],)) == [[0, 1]]
assert candidate(*([{'x': 1}, {'x': 2}],)) == []
assert candidate(*([{'A': 1, 'B': 2}, {'A': 2, 'B': 2}, {'A': 1, 'B': 3}],)) == [[1, 2]]
ass... | 11 | 10 | 21 | 8 | 36 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04954 | strings_and_text_processing | Custom tokenization, run-length / LZ-style lossless compression and decompression | false | medium-hard | Run-length tokenization with lossless integer counts | run_length_compress | You are to implement a lossless run‑length style compression for ASCII strings.
**Function signature**
```python
def run_length_compress(s: str) -> str:
```
**Compression rules**
1. The input `s` consists only of printable ASCII characters (code points 32‑126). It may be empty.
2. The string is parsed from left to ri... | def run_length_compress(s: str) -> str:
# Edge case: empty string
if not s:
return ""
result_parts = []
prev_char = s[0]
count = 1
for ch in s[1:]:
if ch == prev_char:
count += 1
else:
# emit previous run
if count == 1:
... | def run_length_compress(s: str) -> str:
if not s:
return ""
result = []
current_char = s[0]
count = 1
for i in range(1, len(s)):
if s[i] == current_char:
count += 1
else:
# Encode the current run
result.append(current_char)
... | def check(candidate):
assert candidate(*('',)) == ''
assert candidate(*('A',)) == 'A'
assert candidate(*('AA',)) == 'A2'
assert candidate(*('ABABAB',)) == 'ABABAB'
assert candidate(*('AAAABBBCCDAA',)) == 'A4B3C2DA2'
assert candidate(*('Hello World!',)) == 'Hel2o World!'
assert candidate(*('1... | 8 | 10 | 18 | 18 | 24 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05301 | state_machines_and_systems | Vector-clock / Lamport timestamp causality comparator and concurrent event detector | false | medium | Vector Clock Causality Comparator | compare_vector_clocks | You are to implement a function `compare_vector_clocks(clock_a: dict, clock_b: dict) -> dict` that determines the causal relationship between two vector clocks.
Each vector clock is represented as a JSON‑object (Python ``dict``) that maps a *process identifier* (a non‑empty string consisting of ASCII letters, digits o... | def compare_vector_clocks(clock_a, clock_b):
"""Return the causal relation between two vector clocks.
Parameters
----------
clock_a, clock_b : dict
Mapping from process identifier (str) to non‑negative int timestamp.
Returns
-------
dict
{
"relation": "happens_b... | def compare_vector_clocks(clock_a: dict, clock_b: dict) -> dict:
# Collect all process identifiers from both clocks
all_processes = set(clock_a.keys()) | set(clock_b.keys())
differences = []
a_less_or_equal = True
b_less_or_equal = True
for p in all_processes:
val_a = clock_a.g... | def check(candidate):
assert candidate(*({}, {})) == {'relation': 'equal', 'differences': []}
assert candidate(*({'p': 5}, {'p': 5})) == {'relation': 'equal', 'differences': []}
assert candidate(*({'a': 1, 'b': 2}, {'a': 2, 'b': 2})) == {'relation': 'happens_before', 'differences': ['a']}
assert candida... | 10 | 11 | 21 | 11 | 46 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02156 | strings_and_text_processing | Custom tokenization, run-length / LZ-style lossless compression and decompression | false | hard | Custom LZ‑style lossless compression with bounded window | lz_compress | You are to implement a deterministic loss‑less compression algorithm for ASCII strings.
**Function signature**
```python
def lz_compress(text: str) -> str:
```
- `text` contains only printable ASCII characters (code 32‑126). Its length `n` satisfies `0 ≤ n ≤ 10^4`.
- The function must return a compressed representatio... | def lz_compress(text: str) -> str:
# constants
WINDOW = 20
MIN_MATCH = 2
result = []
i = 0
n = len(text)
while i < n:
# define window bounds
win_start = max(0, i - WINDOW)
best_len = 0
best_dist = None
# search for longest match in window
# we ... | def lz_compress(text: str) -> str:
if not text:
return ""
n = len(text)
result = []
i = 0
while i < n:
# Define the window: last 20 characters before position i
window_start = max(0, i - 20)
window = text[window_start:i]
# Find the longest m... | def check(candidate):
assert candidate(*('',)) == ''
assert candidate(*('abc',)) == 'abc'
assert candidate(*('abcabc',)) == 'abc[3|3]'
assert candidate(*('aaaaa',)) == 'aa[2|2]a'
assert candidate(*('a[bc]#d',)) == 'a#[bc#]##d'
assert candidate(*('abcdabcdabcdabcd',)) == 'abcd[4|4][8|8]'
asse... | 12 | 8 | 20 | 20 | 42 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07433 | dynamic_programming | 2D grid DP with obstacles, energy/budget constraints, and exact minimum cost | false | hard | Exact‑budget minimum‑cost path in a 2D grid with obstacles | min_cost_path_exact_budget | You are given a rectangular grid with R rows and C columns (1 ≤ R, C ≤ 30). The grid is represented by a list of R lists, each containing C non‑negative integers `grid[r][c]` (0 ≤ grid[r][c] ≤ 10⁴) which denote the *monetary cost* of stepping on that cell.
You are also given a list `obstacles` of coordinate pairs `[r,... | from typing import List, Tuple
import math
def min_cost_path_exact_budget(grid: List[List[int]], obstacles: List[List[int]], budget: int) -> int:
R, C = len(grid), len(grid[0])
# obstacle lookup set for O(1) checks
obs_set = {(r, c) for r, c in obstacles}
# dp step dimension: we only need current and n... | from typing import List
def min_cost_path_exact_budget(grid: List[List[int]], obstacles: List[List[int]], budget: int) -> int:
R = len(grid)
C = len(grid[0])
# Create a set of obstacle coordinates for O(1) lookup
obstacle_set = set()
for obs in obstacles:
obstacle_set.add((obs[0], obs[... | def check(candidate):
assert candidate(*([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 1]], 4)) == 21
assert candidate(*([[0, 0], [0, 0]], [], 1)) == -1
assert candidate(*([[5]], [], 0)) == 5
assert candidate(*([[1, 2], [3, 4]], [], 2)) == 7
assert candidate(*([[1, 1], [1, 1]], [], 4)) == 5
assert can... | 10 | 9 | 19 | 11 | 29 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06787 | binary_search_and_greedy | Parametric binary search on answer (minimize max load, shipping capacity, bandwidth allocation) | false | medium-hard | Minimum Shipping Capacity to Deliver Within D Days | min_max_shipment_capacity | You are given a list of positive integers `weights` where `weights[i]` is the weight of the i‑th package that must be shipped in order, and an integer `days` representing the maximum number of days allowed to ship all packages. Each day you can ship a contiguous subsequence of packages whose total weight does not excee... | from typing import List
def min_max_shipment_capacity(weights: List[int], days: int) -> int:
"""Return the minimal ship capacity to ship all packages within *days*.
Uses parametric binary search on the answer.
"""
# Helper to check feasibility of a given capacity
def can_ship(cap: int) -> bool:
... | from typing import List
def min_max_shipment_capacity(weights: List[int], days: int) -> int:
"""
Returns the smallest integer capacity C such that all packages can be shipped
in order within `days` days, with each day's total weight <= C.
"""
# Lower bound: at least the max weight (since each packa... | def check(candidate):
assert candidate(*([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)) == 15
assert candidate(*([3, 1, 2, 1, 4], 3)) == 4
assert candidate(*([5, 8, 2, 7, 3], 5)) == 8
assert candidate(*([4, 2, 7, 1, 3], 1)) == 17
assert candidate(*([2, 2, 2, 2, 2, 2], 3)) == 4
assert candidate(*([1000, 1,... | 12 | 10 | 22 | 16 | 29 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04293 | dynamic_programming | 2D grid DP with obstacles, energy/budget constraints, and exact minimum cost | false | medium | Minimum Cost Path with Obstacles and Budget | min_energy_path_cost | You are given a rectangular grid of size `m × n` represented as a list of `m` lists, each containing `n` integers. `grid[i][j]` is the energy cost required to step on cell `(i, j)`. A value of `-1` denotes an obstacle; such cells cannot be entered. You start at the top‑left cell `(0, 0)` and must reach the bottom‑right... | def min_energy_path_cost(grid, budget):
from math import inf
if not grid or not grid[0]:
return -1
m, n = len(grid), len(grid[0])
# start or end blocked
if grid[0][0] == -1 or grid[m-1][n-1] == -1:
return -1
# dp[j] = minimum cost to reach cell (i, j) in current row
dp = [inf... | from typing import List
def min_energy_path_cost(grid: List[List[int]], budget: int) -> int:
m = len(grid)
n = len(grid[0])
# Check if start or end is obstacle
if grid[0][0] == -1 or grid[m-1][n-1] == -1:
return -1
# Initialize DP array with infinity
# We use O(n) space: dp[j]... | def check(candidate):
assert candidate(*([[5]], 5)) == 5
assert candidate(*([[5]], 4)) == -1
assert candidate(*([[-1, 1], [1, 1]], 10)) == -1
assert candidate(*([[1, 1], [1, -1]], 10)) == -1
assert candidate(*([[1, 2, 3], [4, -1, 5], [6, 7, 8]], 19)) == 19
assert candidate(*([[1, 2, 3], [4, -1, ... | 13 | 11 | 24 | 8 | 27 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03231 | state_machines_and_systems | Consistent hashing ring simulator (sorted ring positions, key migration count on node changes) | false | medium | Consistent Hashing Ring Migration Counter | count_migrated_keys | You are to implement a simulator for a Consistent Hashing ring.
**Function signature**
```python
def count_migrated_keys(node_positions: List[int], keys: List[int], operation: str, node_position: int) -> int:
```
- `node_positions` – a list of distinct integers in the range `[0, 2**32 - 1]` representing existing virtu... | import bisect
from typing import List
def _assign(hash_val: int, nodes: List[int]) -> int:
# nodes is sorted list
idx = bisect.bisect_left(nodes, hash_val)
if idx < len(nodes):
return nodes[idx]
return nodes[0]
def count_migrated_keys(node_positions: List[int], keys: List[int], operation: str,... | from typing import List
import bisect
def count_migrated_keys(node_positions: List[int], keys: List[int], operation: str, node_position: int) -> int:
if not keys:
return 0
# Create a sorted list of current nodes for efficient lookup
current_nodes = sorted(node_positions)
n = len(current_no... | def check(candidate):
assert candidate(*([], [1, 2, 3], 'add', 0)) == 3
assert candidate(*([], [1, 2], 'remove', 5)) == 0
assert candidate(*([10], [5, 15, 25], 'add', 20)) == 1
assert candidate(*([100], [50, 150], 'remove', 100)) == 2
assert candidate(*([10, 30, 70], [5, 15, 35, 75], 'add', 30)) == ... | 12 | 11 | 23 | 5 | 47 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04037 | binary_search_and_greedy | Multi-server priority queue / load-balancer deterministic event simulation | false | hard | Deterministic Multi-Server Load Balancer Simulation | simulate_load_balancer | You are given a list of `servers` and a list of `tasks`. Each server `i` has an integer processing speed `servers[i]` (units of work per time unit, 1 ≤ servers[i] ≤ 10^6). Each task `j` is represented by a pair `(arrival_time, work)` where `arrival_time` is a non‑negative integer (time when the task becomes ready) and ... | import heapq
import math
from typing import List, Tuple
def simulate_load_balancer(servers: List[int], tasks: List[Tuple[int, int]]) -> List[int]:
if not servers:
raise ValueError("servers list must not be empty")
n = len(servers)
# idle servers stored as a min‑heap of indices
idle = list(range... | import heapq
from math import ceil
from typing import List, Tuple
def simulate_load_balancer(servers: List[int], tasks: List[Tuple[int, int]]) -> List[int]:
if not servers:
raise ValueError("servers list cannot be empty")
n_servers = len(servers)
n_tasks = len(tasks)
if n_tasks == 0:
... | def check(candidate):
assert candidate(*([5, 3], [(0, 10), (0, 5), (2, 6)])) == [0, 1, 0]
assert candidate(*([2, 2, 2], [(1, 3), (1, 3), (1, 3), (5, 4)])) == [0, 1, 2, 0]
assert candidate(*([4], [(0, 5), (1, 3), (2, 7)])) == [0, 0, 0]
assert candidate(*([1, 1], [(0, 2), (0, 2), (2, 1), (2, 1)])) == [0, ... | 12 | 12 | 24 | 14 | 37 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02703 | dynamic_programming | 2D grid DP with obstacles, energy/budget constraints, and exact minimum cost | false | medium | Minimum Cost Path in a Grid with Obstacles and Energy Budget | min_cost_path_with_budget | You are given a rectangular grid of size `n × m` ( `1 ≤ n, m ≤ 100` ). The grid is represented as a list of `n` lists, each containing `m` integers. Each cell `(i, j)` has one of the following values:
* `-1` – the cell is blocked and cannot be entered.
* a non‑negative integer `c` ( `0 ≤ c ≤ 10^4` ) – the cost of **en... | import heapq
from typing import List, Tuple
def min_cost_path_with_budget(grid: List[List[int]], start: Tuple[int, int], end: Tuple[int, int], budget: int) -> int:
n = len(grid)
m = len(grid[0]) if n else 0
sx, sy = start
ex, ey = end
# start or end blocked
if grid[sx][sy] == -1 or grid[ex][ey]... | from typing import List, Tuple
import heapq
def min_cost_path_with_budget(grid: List[List[int]], start: Tuple[int, int], end: Tuple[int, int], budget: int) -> int:
n = len(grid)
m = len(grid[0])
sx, sy = start
ex, ey = end
# Check if start or end is blocked
if grid[sx][sy] == -1 or gr... | def check(candidate):
assert candidate(*([[5]], (0, 0), (0, 0), 5)) == 5
assert candidate(*([[5]], (0, 0), (0, 0), 4)) == -1
assert candidate(*([[-1, 1], [2, 3]], (0, 0), (1, 1), 10)) == -1
assert candidate(*([[1, 2], [3, -1]], (0, 0), (1, 1), 10)) == -1
assert candidate(*([[1, 2], [3, 4]], (0, 0), ... | 11 | 9 | 20 | 7 | 34 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02433 | dynamic_programming | 2D grid DP with obstacles, energy/budget constraints, and exact minimum cost | false | medium | Exact Budget Minimum Cost Path in a Grid with Obstacles | exact_budget_min_cost | You are given a rectangular grid of size `m` rows by `n` columns. The grid is represented as a list of `m` strings, each of length `n`. Each character describes a cell:
- `'0'` – free cell, can be entered without additional cost.
- `'1'` – obstacle, cannot be entered.
- a digit `'2'`‑`'9'` – free cell that adds the num... | from typing import List
def exact_budget_min_cost(grid: List[str], budget: int) -> int:
if not grid:
return -1
m, n = len(grid), len(grid[0])
# Pre‑convert cell costs, -1 for obstacle
cost = [[-1] * n for _ in range(m)]
for i in range(m):
if len(grid[i]) != n:
return -1 ... | from typing import List
def exact_budget_min_cost(grid: List[str], budget: int) -> int:
if not grid or not grid[0]:
return -1
m = len(grid)
n = len(grid[0])
# Helper to get cost of a cell
def cell_cost(r, c):
ch = grid[r][c]
if ch == '0':
return 0
... | def check(candidate):
assert candidate(*(['0'], 0)) == 0
assert candidate(*(['2'], 2)) == 2
assert candidate(*(['2'], 3)) == -1
assert candidate(*(['00', '00'], 0)) == 0
assert candidate(*(['02', '30'], 5)) == -1
assert candidate(*(['02', '30'], 3)) == 3
assert candidate(*(['023', '104', '21... | 12 | 9 | 21 | 6 | 49 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07042 | graph_and_network_algorithms | Minimum spanning tree / network clustering with mandatory or forbidden edges | false | medium-hard | MST with Mandatory and Forbidden Edges | mst_with_constraints | You are given an undirected weighted graph with `n` vertices numbered from `0` to `n-1`. The graph is described by a list `edges`, where each element is a tuple `(u, v, w)` meaning there is an undirected edge between vertices `u` and `v` with positive integer weight `w`. Additionally you are given two lists of edges:
... | from typing import List, Tuple
import heapq
def mst_with_constraints(n: int, edges: List[Tuple[int, int, int]], mandatory: List[Tuple[int, int]], forbidden: List[Tuple[int, int]]) -> int:
# Helper: Union‑Find
class DSU:
def __init__(self, size: int):
self.parent = list(range(size))
... | from typing import List, Tuple
import heapq
def mst_with_constraints(n: int, edges: List[Tuple[int, int, int]], mandatory: List[Tuple[int, int]], forbidden: List[Tuple[int, int]]) -> int:
# Build a set of forbidden edges (normalized as frozensets of 2 elements)
forbidden_set = set()
for u, v in forbidden:
... | def check(candidate):
assert candidate(*(1, [], [], [])) == 0
assert candidate(*(3, [(0, 1, 4), (1, 2, 5), (0, 2, 6)], [(0, 1)], [])) == 9
assert candidate(*(2, [(0, 1, 3)], [(0, 0)], [])) == -1
assert candidate(*(3, [(0, 1, 1), (1, 2, 2), (0, 2, 3)], [(0, 1), (1, 2), (0, 2)], [])) == -1
assert cand... | 12 | 9 | 21 | 7 | 82 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02476 | strings_and_text_processing | Fuzzy string search, k-mismatch pattern finder, and palindrome partitioning | false | medium-hard | Fuzzy Palindrome Partitioning with Pattern Constraint | find_fuzzy_palindrome_partitions | Write a function `find_fuzzy_palindrome_partitions(text: str, pattern: str, k: int) -> List[List[str]]` that returns **all** possible ways to split the entire string `text` into a sequence of non‑empty contiguous substrings (a *partition*) satisfying **both** of the following conditions:
1. **Fuzzy palindrome conditio... | import itertools
from typing import List
def is_k_palindrome(s: str, k: int) -> bool:
mismatches = 0
n = len(s)
for i in range(n // 2):
if s[i] != s[n - 1 - i]:
mismatches += 1
if mismatches > k:
return False
return True
def find_fuzzy_palindrome_partiti... | from typing import List
def find_fuzzy_palindrome_partitions(text: str, pattern: str, k: int) -> List[List[str]]:
n = len(text)
# Precompute which substrings are valid (fuzzy palindrome AND contain pattern)
# valid[i][j] = True if text[i:j+1] is a valid substring
valid = [[False] * n for _ in rang... | def check(candidate):
assert candidate(*('a', 'a', 0)) == [['a']]
assert candidate(*('ab', 'a', 0)) == []
assert candidate(*('aba', 'a', 0)) == [['aba']]
assert candidate(*('abac', 'a', 1)) == [['a', 'bac'], ['ab', 'ac']]
assert candidate(*('abacaba', 'a', 0)) == [['a', 'bacab', 'a'], ['abacaba']]
... | 14 | 6 | 20 | 15 | 37 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02999 | business_logic_and_fintech | Progressive tax bracket & tiered fee calculator with exact integer-cent rounding | false | hard | Progressive Tax and Tiered Fee Calculator with Cent Precision | compute_total_charge | You are asked to implement a function `compute_total_charge(income: int, amount: int) -> int` that calculates the total monetary charge (tax plus service fee) for a financial transaction, expressed in **integer cents**.
The calculation consists of two independent parts:
1. **Progressive Income Tax**
- The taxpayer... | def compute_total_charge(income: int, amount: int) -> int:
# ---- Tax calculation ----
tax = 0.0
# Bracket 1: $0 - $10,000 (0%)
# Bracket 2: $10,000 - $30,000 (10%)
if income > 10_000:
taxable = min(income, 30_000) - 10_000
tax += taxable * 0.10
# Bracket 3: $30,000 - $100,000 (2... | def compute_total_charge(income: int, amount: int) -> int:
# Calculate progressive income tax
tax_dollars = 0.0
if income > 0:
# Bracket 1: $0 - $10,000 at 0%
bracket1 = min(income, 10000)
tax_dollars += bracket1 * 0.0
# Bracket 2: $10,000 - $30,000 at 10%
... | def check(candidate):
assert candidate(*(0, 0)) == 500
assert candidate(*(9999, 999)) == 500
assert candidate(*(10000, 1000)) == 2000
assert candidate(*(15000, 5000)) == 52000
assert candidate(*(30000, 9999)) == 202000
assert candidate(*(45000, 12345)) == 505000
assert candidate(*(100000, 49... | 14 | 9 | 23 | 19 | 31 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04811 | state_machines_and_systems | Consistent hashing ring simulator (sorted ring positions, key migration count on node changes) | false | hard | Consistent Hashing Ring Migration Counter | count_migrated_keys | You are to implement a simulator for a consistent hashing ring.
**Function signature**
```python
def count_migrated_keys(old_nodes: List[int], new_nodes: List[int], keys: List[int]) -> int:
```
All arguments are JSON‑serialisable Python built‑ins.
**Definitions**
* The ring is a circle of integer positions from `0` t... | import bisect
from typing import List
def _responsible(node_list: List[int], key: int) -> int:
"""Return the responsible node for *key* in *node_list*.
If *node_list* is empty, return -1 as a sentinel for "no node".
"""
if not node_list:
return -1
idx = bisect.bisect_left(node_list, key)
... | import bisect
def count_migrated_keys(old_nodes: list, new_nodes: list, keys: list) -> int:
"""
Count the number of keys that migrate to a different node when transitioning
from old_nodes to new_nodes on a consistent hashing ring.
"""
# If both node lists are empty, no keys can be assigned, so no m... | def check(candidate):
assert candidate(*([], [], [])) == 0
assert candidate(*([], [], [1, 2, 3])) == 0
assert candidate(*([10, 30], [10, 20, 30], [])) == 0
assert candidate(*([10, 30, 70], [10, 30, 50, 70], [5, 10, 33, 69, 71])) == 1
assert candidate(*([0, 2147483647], [0], [0, 1, 2147483646])) == 2... | 12 | 11 | 23 | 8 | 25 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-08142 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | medium | Lexicographically Smallest Topological Order and Critical Path Duration | schedule_tasks | You are given a directed acyclic graph (DAG) representing tasks and their prerequisite relationships.
**Function signature**
```python
def schedule_tasks(n: int, edges: List[Tuple[int, int]], durations: List[int]) -> Tuple[List[int], int]:
```
- `n` (1 ≤ n ≤ 10^5) is the number of tasks, numbered from `0` to `n-1`.
- ... | import heapq
from typing import List, Tuple
def schedule_tasks(n: int, edges: List[Tuple[int, int]], durations: List[int]) -> Tuple[List[int], int]:
# Edge case: empty graph
if n == 0:
return ([], 0)
# Build adjacency list and indegree array
adj: List[List[int]] = [[] for _ in range(n)]
in... | from typing import List, Tuple
import heapq
def schedule_tasks(n: int, edges: List[Tuple[int, int]], durations: List[int]) -> Tuple[List[int], int]:
if n == 0:
return ([], 0)
# Build adjacency list and in-degree array
adj = [[] for _ in range(n)]
in_degree = [0] * n
for u, v in ed... | def check(candidate):
assert candidate(*(0, [], [])) == ([], 0)
assert candidate(*(1, [], [10])) == ([0], 10)
assert candidate(*(2, [(0, 1)], [3, 5])) == ([0, 1], 8)
assert candidate(*(2, [], [4, 2])) == ([0, 1], 4)
assert candidate(*(5, [(0, 2), (1, 2), (2, 3), (2, 4)], [3, 2, 4, 1, 5])) == ([0, 1,... | 12 | 10 | 22 | 22 | 44 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02861 | state_machines_and_systems | Consistent hashing ring simulator (sorted ring positions, key migration count on node changes) | false | hard | Consistent Hashing Ring Migration Counter | count_migrated_keys | You are given three arguments:
1. `old_nodes` – a list of distinct non‑negative integers, each representing the position of a node on a consistent‑hashing ring. The ring has size `M = 2**32` (positions range from `0` to `M-1`). The list may be empty.
2. `new_nodes` – a list of distinct non‑negative integers, the posit... | import bisect
from typing import List
def _responsible(node_positions: List[int], h: int) -> int:
"""Return the responsible node for hash h given a *sorted* list of positions.
Assumes node_positions is non‑empty.
"""
idx = bisect.bisect_left(node_positions, h)
if idx == len(node_positions):
... | from bisect import bisect_left
def count_migrated_keys(old_nodes: list, new_nodes: list, keys: list) -> int:
"""
Compute the number of keys that change their responsible node when the ring
transitions from old_nodes to new_nodes.
"""
# If either node list is empty, no key can have a responsible nod... | def check(candidate):
assert candidate(*([10, 30, 70], [20, 70], [5, 10, 25, 30, 65, 90])) == 5
assert candidate(*([0], [0], [0, 1, 4294967295])) == 0
assert candidate(*([], [5, 15], [0, 5, 10])) == 0
assert candidate(*([5, 15], [], [0, 5, 10])) == 0
assert candidate(*([], [], [])) == 0
assert c... | 14 | 10 | 24 | 8 | 26 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06963 | dynamic_programming | 2D grid DP with obstacles, energy/budget constraints, and exact minimum cost | false | medium | Minimum Energy Path in a Grid with Obstacles and Budget | min_energy_path | You are given a rectangular grid represented as a list of lists of integers. Each cell contains a non‑negative integer `c` that denotes the amount of energy required to step on that cell. Some cells are blocked and cannot be entered; a blocked cell is represented by the integer `-1`.
You start at the top‑left cell `(0... | from typing import List
def min_energy_path(grid: List[List[int]], budget: int) -> int:
n = len(grid)
m = len(grid[0])
# dp[j] will hold the minimum cost to reach cell (i, j) for current row i.
INF = 10**18
dp = [INF] * m
for i in range(n):
new_dp = [INF] * m
for j in range(m):
... | from typing import List
def min_energy_path(grid: List[List[int]], budget: int) -> int:
n = len(grid)
m = len(grid[0])
# If start or end is blocked (though spec says they aren't), handle gracefully
if grid[0][0] == -1 or grid[n-1][m-1] == -1:
return -1
# DP array: dp[j] represents... | def check(candidate):
assert candidate(*([[1, 2, 3], [4, -1, 5], [6, 7, 8]], 20)) == 19
assert candidate(*([[0, 0], [0, 0]], 0)) == 0
assert candidate(*([[1, -1], [-1, 1]], 10)) == -1
assert candidate(*([[5, 5], [5, 5]], 10)) == -1
assert candidate(*([[42]], 42)) == 42
assert candidate(*([[42]],... | 12 | 10 | 22 | 11 | 29 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-08347 | binary_search_and_greedy | Parametric binary search on answer (minimize max load, shipping capacity, bandwidth allocation) | false | medium-hard | Minimize Maximum Load with Contiguous Task Partitioning | min_max_load | You are given a list of positive integers `tasks` representing the processing time of sequential tasks, and an integer `workers` (1 ≤ workers ≤ len(tasks)). The tasks must be assigned to the workers in the original order, and each worker receives a contiguous block of tasks (a worker may receive zero tasks). Define the... | from typing import List
def min_max_load(tasks: List[int], workers: int) -> int:
# Helper: can we split tasks into at most `workers` groups such that each group sum <= limit?
def feasible(limit: int) -> bool:
needed = 1 # start with first worker
current = 0
for t in tasks:
... | from typing import List
def min_max_load(tasks: List[int], workers: int) -> int:
if not tasks:
return 0
n = len(tasks)
# Edge cases
if workers >= n:
return max(tasks)
if workers == 1:
return sum(tasks)
# Binary search on the answer
# Lower bound: ... | def check(candidate):
assert candidate(*([7, 2, 5, 10, 8], 2)) == 18
assert candidate(*([1, 2, 3, 4, 5], 3)) == 6
assert candidate(*([5, 1, 4, 2], 4)) == 5
assert candidate(*([10, 20, 30], 1)) == 60
assert candidate(*([4, 4, 4, 4, 4, 4], 5)) == 8
assert candidate(*([1000000000, 999999999, 999999... | 12 | 10 | 22 | 19 | 28 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05256 | strings_and_text_processing | Fuzzy string search, k-mismatch pattern finder, and palindrome partitioning | false | medium | k-Mismatch Palindromic Partition Finder | find_min_pal_partition | You are given a lowercase alphabetic string **s** (1 ≤ len(s) ≤ 200) and an integer **k** (0 ≤ k ≤ 5). A *k‑mismatch palindrome* is a string that can become a palindrome after changing at most **k** of its characters (each change can replace a character by any lowercase letter). A *palindromic partition* of **s** is a ... | def find_min_pal_partition(s: str, k: int) -> int:
n = len(s)
# precompute mismatch count for every substring [i, j)
mism = [[0] * (n + 1) for _ in range(n)]
for i in range(n):
for j in range(i + 1, n + 1):
# compute mismatches for s[i:j]
left, right = i, j - 1
... | def find_min_pal_partition(s: str, k: int) -> int:
n = len(s)
if n == 0:
return -1
# Precompute is_k_mismatch[i][j] = True if s[i:j+1] is a k-mismatch palindrome
# We can compute this efficiently
is_k_pal = [[False] * n for _ in range(n)]
for i in range(n):
for j in ran... | def check(candidate):
assert candidate(*('a', 0)) == 1
assert candidate(*('ab', 0)) == 2
assert candidate(*('ab', 1)) == 1
assert candidate(*('aba', 0)) == 1
assert candidate(*('abac', 1)) == 2
assert candidate(*('abcde', 2)) == 1
assert candidate(*('aaaaaa', 0)) == 1
assert candidate(*(... | 14 | 7 | 21 | 5 | 27 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02713 | parsing_and_compilers | Nested bracket/macro template expander with syntax and cycle error handling | false | medium-hard | Nested Macro Template Expander with Cycle Detection | expand_template | You are to implement a function `expand_template(template: str, macros: dict) -> str` that expands a text template using a dictionary of macro definitions.
**Template syntax**
- A placeholder is written as `{{NAME}}` where `NAME` consists of one or more ASCII letters (`A‑Z`, `a‑z`) and underscores (`_`).
- Placeholder... | import re
from typing import Dict, Set
def expand_template(template: str, macros: Dict[str, str]) -> str:
placeholder_pattern = re.compile(r"\{\{([A-Za-z_]+)\}\}")
# Cache for already fully expanded macros to avoid recomputation within a single call.
# This cache does NOT break cycle detection because we ... | import re
def expand_template(template: str, macros: dict) -> str:
# Pattern to match placeholders {{NAME}}
placeholder_pattern = re.compile(r'\{\{([A-Za-z_][A-Za-z_]*)\}\}')
# Cache for already expanded macros to avoid re-expanding if not in cycle
# But per spec: "each occurrence is expanded anew... | def check(candidate):
assert candidate(*('Hello, {{user}}!', {'user': 'Alice'})) == 'Hello, Alice!'
assert candidate(*('{{greet}}', {'greet': 'Hi {{name}}', 'name': '{{first}} {{last}}', 'first': 'Bob', 'last': 'Smith'})) == 'Hi Bob Smith'
assert candidate(*('{{a}}', {'a': '{{b}}', 'b': '{{c}}', 'c': '{{a}}... | 14 | 9 | 23 | 18 | 39 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03778 | math_and_combinatorics | Modular arithmetic, prime factorization, Euler totient, and matrix exponentiation mod M | false | medium-hard | Fibonacci-like sequence modulo M and Euler totient | fib_mod_and_totient | You are to implement the function `fib_mod_and_totient(N: int, A: int, B: int, M: int) -> dict`.
The function works with four integer arguments:
- `N` (0 ≤ N ≤ 10^18) – the index of the sequence to compute.
- `A` (0 ≤ A < M) – the value of S₀.
- `B` (0 ≤ B < M) – the value of S₁.
- `M` (2 ≤ M ≤ 10^9) – the modulus.
D... | import math
from typing import Dict
def _mat_mult(a, b, mod):
# multiply 2x2 matrices a and b modulo mod
return [
[(a[0][0]*b[0][0] + a[0][1]*b[1][0]) % mod, (a[0][0]*b[0][1] + a[0][1]*b[1][1]) % mod],
[(a[1][0]*b[0][0] + a[1][1]*b[1][0]) % mod, (a[1][0]*b[0][1] + a[1][1]*b[1][1]) % mod]
]
... | def fib_mod_and_totient(N: int, A: int, B: int, M: int) -> dict:
if M < 2:
raise ValueError("M must be at least 2")
# Compute S_N using matrix exponentiation
# [S_n, S_{n-1}]^T = [[1, 1], [1, 0]]^(n-1) * [S_1, S_0]^T for n >= 1
# For n=0, S_0 = A
# For n=1, S_1 = B
def mat_mult... | def check(candidate):
assert candidate(*(0, 5, 8, 13)) == {'value': 5, 'totient': 12}
assert candidate(*(1, 2, 3, 100)) == {'value': 3, 'totient': 40}
assert candidate(*(5, 2, 3, 100)) == {'value': 21, 'totient': 40}
assert candidate(*(10, 7, 11, 101)) == {'value': 35, 'totient': 100}
assert candida... | 10 | 11 | 21 | 16 | 51 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06857 | binary_search_and_greedy | Two-pointer / prefix-sum subarray bounds with negative numbers and modular constraints | false | hard | Count Subarrays with Given Modulo Sum | count_subarrays_modular | You are to implement a function `count_subarrays_modular(arr, m, target)` that counts how many contiguous sub‑arrays of the integer list `arr` have a sum whose remainder when divided by the positive integer `m` equals `target`.
**Function signature**
```python
def count_subarrays_modular(arr: List[int], m: int, target... | import collections
from typing import List
def count_subarrays_modular(arr: List[int], m: int, target: int) -> int:
"""Return the number of contiguous sub‑arrays whose sum modulo m equals target.
The implementation uses prefix sums and a frequency dictionary of remainders.
"""
# Frequency of prefix rem... | from typing import List
def count_subarrays_modular(arr: List[int], m: int, target: int) -> int:
"""
Counts the number of contiguous subarrays whose sum modulo m equals target.
Uses prefix sums and a frequency map of prefix sum remainders.
For each prefix sum prefix[i], we want to find how many pr... | def check(candidate):
assert candidate(*([3, 1, 4, 1, 5], 5, 3)) == 2
assert candidate(*([-2, -3, 7, 0], 4, 1)) == 1
assert candidate(*([], 10, 0)) == 0
assert candidate(*([0, 0, 0], 7, 0)) == 6
assert candidate(*([0, 0, 0, 0], 3, 2)) == 0
assert candidate(*([10], 6, 4)) == 1
assert candidat... | 14 | 12 | 26 | 8 | 20 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-08368 | data_engineering_and_pipelines | CDC (Change Data Capture) event compactor with idempotency keys and tombstones | false | medium-hard | CDC Event Compactor with Idempotency and Tombstones | compact_cdc_events | You are given a list of change‑data‑capture (CDC) events that describe inserts/updates (type "upsert") or deletions (type "delete") of records in a source system. Each event is represented by a JSON object (Python dict) with the following fields:
- "id": a string that uniquely identifies the logical record the event r... | def compact_cdc_events(events):
"""Return the compacted CDC event list as described in the problem statement.
The function works in O(N log N) time by scanning once to find the latest
event per id (while checking for duplicate seq) and then sorting the ids.
"""
if not events:
return []
... | from typing import List, Dict
def compact_cdc_events(events: List[Dict]) -> List[Dict]:
"""
Compact a list of CDC events by keeping only the latest event (highest seq)
for each distinct id. If the latest event is a delete, it becomes a tombstone.
The result is sorted by id in ascending lexicographic o... | def check(candidate):
assert candidate(*([],)) == []
assert candidate(*([{'id': 'x', 'seq': 0, 'type': 'upsert', 'payload': {'a': 1}}],)) == [{'id': 'x', 'seq': 0, 'type': 'upsert', 'payload': {'a': 1}}]
assert candidate(*([{'id': 'y', 'seq': 5, 'type': 'delete', 'payload': None}],)) == [{'id': 'y', 'seq': ... | 10 | 10 | 20 | 19 | 28 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06249 | state_machines_and_systems | Vector-clock / Lamport timestamp causality comparator and concurrent event detector | false | medium | Vector Clock Causality Comparator | compare_vector_clocks | You are given two vector clocks, each represented as a list of non‑negative integers of the same length. A vector clock V = [v1, v2, ..., vn] records the logical time of a process in a distributed system. The causality relation between two vector clocks A and B is defined as follows:
* A **happened‑before** B (denoted... | def compare_vector_clocks(a, b):
# Validate lengths first
if len(a) != len(b):
return "INVALID"
# Flags to track comparisons
less = False # a[i] < b[i] for some i
greater = False # a[i] > b[i] for some i
for av, bv in zip(a, b):
if av < bv:
less = True
elif ... | def compare_vector_clocks(a: list, b: list) -> str:
if len(a) != len(b):
return "INVALID"
n = len(a)
all_equal = True
a_less_than_b = False
b_less_than_a = False
for i in range(n):
if a[i] < b[i]:
a_less_than_b = True
elif a[i] > b[i]:
b_... | def check(candidate):
assert candidate(*([1, 2, 3], [1, 2, 4])) == 'BEFORE'
assert candidate(*([1, 2, 4], [1, 2, 3])) == 'AFTER'
assert candidate(*([5, 0, 2], [5, 0, 2])) == 'EQUAL'
assert candidate(*([2, 1], [1, 2])) == 'CONCURRENT'
assert candidate(*([3, 5, 2], [4, 4, 2])) == 'CONCURRENT'
asse... | 14 | 8 | 22 | 5 | 24 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04889 | business_logic_and_fintech | Prorated SaaS subscription billing, mid-cycle tier upgrades, and exact integer-cent ledger | false | hard | Prorated SaaS Subscription Billing with Mid‑Cycle Tier Upgrades | calculate_total_cents | You are given the billing history of a single customer for a SaaS product that offers several subscription tiers. Each tier has a fixed monthly price expressed in whole cents. The customer may upgrade to a higher tier at any day of a month; downgrades are not allowed. When an upgrade occurs, the customer is charged a p... | def calculate_total_cents(tiers, events):
total = 0
# first event: full month price
first_tier = events[0]["tier"]
total += tiers[first_tier]
prev_tier = first_tier
for ev in events[1:]:
new_tier = ev["tier"]
if new_tier == prev_tier:
continue
price_diff = tie... | def calculate_total_cents(tiers: dict, events: list) -> int:
total = 0
if not events:
return 0
# Process the first event: full month price
first_event = events[0]
first_tier = first_event['tier']
first_price = tiers[first_tier]
total += first_price
current_tier = first_... | def check(candidate):
assert candidate(*({'basic': 1000}, [{'day': 1, 'tier': 'basic'}])) == 1000
assert candidate(*({'basic': 2000}, [{'day': 25, 'tier': 'basic'}])) == 2000
assert candidate(*({'basic': 1000, 'pro': 3000}, [{'day': 1, 'tier': 'basic'}, {'day': 28, 'tier': 'pro'}])) == 1200
assert candi... | 12 | 11 | 23 | 19 | 16 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03406 | strings_and_text_processing | Fuzzy string search, k-mismatch pattern finder, and palindrome partitioning | false | medium-hard | Fuzzy Pattern Occurrences with Minimal Palindrome Partitions | fuzzy_pattern_palindrome_counts | Write a function `fuzzy_pattern_palindrome_counts(text: str, pattern: str, k: int) -> List[int]` that performs two tasks.
1. **Fuzzy pattern search**: Find every index `i` (0‑based) such that the substring `text[i:i+len(pattern)]` exists and differs from `pattern` in at most `k` positions (i.e., Hamming distance ≤ k).... | def fuzzy_pattern_palindrome_counts(text: str, pattern: str, k: int) -> list:
# Guard against invalid k
if k < 0:
k = 0
n, m = len(text), len(pattern)
if m == 0 or m > n:
return []
# Helper: compute mismatches for each window using sliding technique
mismatches = [] # list of st... | from typing import List
def fuzzy_pattern_palindrome_counts(text: str, pattern: str, k: int) -> List[int]:
# Handle edge cases
if not pattern or len(pattern) > len(text):
return []
# Treat negative k as 0
if k < 0:
k = 0
n = len(text)
m = len(pattern)
# Step 1... | def check(candidate):
assert candidate(*('abacaba', 'aba', 0)) == [1, 1]
assert candidate(*('abcdefg', 'abc', 1)) == [3]
assert candidate(*('aaaaa', 'aa', 0)) == [1, 1, 1, 1]
assert candidate(*('abcde', 'xyz', 2)) == []
assert candidate(*('abcabcabc', 'abc', 0)) == [3, 3, 3]
assert candidate(*('... | 14 | 9 | 23 | 8 | 57 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03150 | math_and_combinatorics | Exact rational arithmetic using integer pairs, continued fractions, and linear Diophantine checks | false | medium | Count Continued‑Fraction Convergents Satisfying a Linear Diophantine Equation | count_convergent_solutions | Write a function `count_convergent_solutions(num: int, den: int, a: int, b: int, c: int) -> int` that works as follows.
* `num` and `den` describe a rational number `r = num / den`. Both are non‑negative integers, `den > 0`. The fraction may be non‑reduced; you must treat it as the exact rational value.
* Compute the ... | def count_convergent_solutions(num: int, den: int, a: int, b: int, c: int) -> int:
"""Return the number of convergents of num/den that satisfy a*p + b*q == c.
Parameters
----------
num, den : int
Numerator and denominator of the rational number (den > 0).
a, b, c : int
Coefficients ... | def count_convergent_solutions(num: int, den: int, a: int, b: int, c: int) -> int:
if den <= 0:
raise ValueError("den must be positive")
if not isinstance(num, int) or not isinstance(den, int) or not isinstance(a, int) or not isinstance(b, int) or not isinstance(c, int):
raise ValueError("All in... | def check(candidate):
assert candidate(*(415, 93, 1, -1, 0)) == 0
assert candidate(*(0, 5, 2, 3, 7)) == 0
assert candidate(*(5, 1, 5, 0, 25)) == 1
assert candidate(*(3, 2, 1, 1, 5)) == 1
assert candidate(*(7, 3, -2, 5, 1)) == 2
assert candidate(*(123456789, 98765432, 12345, 67890, 0)) == 0
a... | 10 | 10 | 20 | 3 | 49 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05899 | business_logic_and_fintech | Progressive tax bracket & tiered fee calculator with exact integer-cent rounding | false | medium-hard | Progressive Tax and Tiered Fee Calculator with Exact Cent Rounding | compute_total_charge | You are to implement a function `compute_total_charge(amount_cents: int, tax_brackets: List[Tuple[int, int]], fee_tiers: List[Tuple[int, int]]) -> int`.
**Parameters**
- `amount_cents`: the gross amount of a transaction expressed in **integer cents** (0 ≤ amount_cents ≤ 10^12).
- `tax_brackets`: a list of tuples `(upp... | def compute_total_charge(amount_cents, tax_brackets, fee_tiers):
# Compute progressive tax
total_tax = 0
prev_upper = 0
for upper, rate in tax_brackets:
if upper == -1:
portion = amount_cents - prev_upper
else:
if amount_cents <= prev_upper:
portio... | def compute_total_charge(amount_cents: int, tax_brackets: list, fee_tiers: list) -> int:
if amount_cents == 0:
return 0
# Calculate tax
total_tax_cents = 0
previous_upper = 0
for upper_bound, rate_percent in tax_brackets:
if upper_bound == -1:
# Final bracket: n... | def check(candidate):
assert candidate(*(123456, [(10000, 10), (50000, 20), (-1, 30)], [(20000, 500), (100000, 1000)])) == 155993
assert candidate(*(0, [(-1, 0)], [])) == 0
assert candidate(*(50000, [(10000, 5), (50000, 10), (-1, 15)], [])) == 54500
assert candidate(*(25001, [(-1, 12)], [(25000, 250)]))... | 12 | 12 | 24 | 22 | 25 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07878 | data_engineering_and_pipelines | In-memory relational join / group-by / window-rank engine over list-of-dict records | false | medium | Top N Ranked Records Per Group | top_n_by_group | Write a function `top_n_by_group(records: List[Dict[str, Any]], n: int, reverse: bool = True) -> Dict[str, List[int]]` that processes an in‑memory table represented as a list of dictionaries. Each dictionary has exactly three keys:
- `"group"` (a string) – the group to which the record belongs,
- `"value"` (an integer)... | from typing import List, Dict, Any
def top_n_by_group(records: List[Dict[str, Any]], n: int, reverse: bool = True) -> Dict[str, List[int]]:
"""Return the top *n* record ids per group according to the ranking rules.
The function does not modify the input list.
"""
if not records:
return {}
#... | from typing import List, Dict, Any
def top_n_by_group(records: List[Dict[str, Any]], n: int, reverse: bool = True) -> Dict[str, List[int]]:
# Group records by group name
groups: Dict[str, List[Dict[str, Any]]] = {}
for record in records:
group_name = record['group']
if group_name not in gro... | def check(candidate):
assert candidate(*([{'group': 'A', 'value': 10, 'id': 1}, {'group': 'A', 'value': 20, 'id': 2}, {'group': 'A', 'value': 15, 'id': 3}, {'group': 'B', 'value': 5, 'id': 4}, {'group': 'B', 'value': 7, 'id': 5}], 2, True)) == {'A': [2, 3], 'B': [5, 4]}
assert candidate(*([{'group': 'A', 'value... | 12 | 11 | 23 | 18 | 22 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03572 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | hard | Lexicographically Minimal Topological Order and Critical Path in a DAG | schedule_tasks | You are given a directed acyclic graph (DAG) that represents a set of tasks and their prerequisite relationships.
Each task is described by a dictionary with three keys:
* "id": a unique non‑empty string consisting of alphanumeric characters (A‑Z, a‑z, 0‑9). No two tasks share the same id.
* "duration": a positive int... | import heapq
from collections import defaultdict, deque
from typing import List, Dict, Tuple
def schedule_tasks(tasks: List[Dict]) -> Tuple[List[str], int]:
if not tasks:
return ([], 0)
# Build graph structures
indeg = {}
graph = defaultdict(list) # u -> list of v
duration = {}
for t ... | import heapq
from collections import defaultdict, deque
def schedule_tasks(tasks: list[dict]) -> tuple[list[str], int]:
if not tasks:
return ([], 0)
# Build adjacency list and in-degree count
# We need to map id -> task info
task_map = {}
for t in tasks:
task_map[t['id']] = t
... | def check(candidate):
assert candidate(*([],)) == ([], 0)
assert candidate(*([{'id': 'A', 'duration': 5, 'prerequisites': []}],)) == (['A'], 5)
assert candidate(*([{'id': 'b', 'duration': 2, 'prerequisites': []}, {'id': 'a', 'duration': 3, 'prerequisites': []}],)) == (['a', 'b'], 3)
assert candidate(*([... | 10 | 11 | 21 | 19 | 50 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05327 | binary_search_and_greedy | Two-pointer / prefix-sum subarray bounds with negative numbers and modular constraints | false | hard | Count subarrays with given modular sum under negative numbers | count_modular_subarrays | You are given a list of integers `arr`, an integer modulus `mod` (mod > 0), and an integer `target` (0 <= target < mod). A subarray is a contiguous slice of `arr` (possibly the whole array, but never empty). Define the *modular sum* of a subarray as the sum of its elements taken modulo `mod` (the Python expression `(su... | def count_modular_subarrays(arr, mod, target):
"""Return the number of contiguous subarrays whose sum modulo `mod` equals `target`.
Args:
arr (list[int]): list of integers, length >= 1.
mod (int): positive modulus.
target (int): desired remainder, 0 <= target < mod.
Returns:
... | from typing import List
from collections import defaultdict
def count_modular_subarrays(arr: List[int], mod: int, target: int) -> int:
"""
Count the number of subarrays whose modular sum equals target.
Uses prefix sums and a hash map to achieve O(n) time complexity.
Key insight:
- Let pre... | def check(candidate):
assert candidate(*([3, -1, 4, -2], 5, 2)) == 2
assert candidate(*([0, 0, 0], 3, 0)) == 6
assert candidate(*([7], 5, 2)) == 1
assert candidate(*([7], 5, 3)) == 0
assert candidate(*([-5, 10, -3, 1, 2], 7, 4)) == 1
assert candidate(*([1, 2, 3, 4, 5], 1000000000, 123)) == 0
... | 12 | 10 | 22 | 7 | 23 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02979 | business_logic_and_fintech | Progressive tax bracket & tiered fee calculator with exact integer-cent rounding | false | medium | Progressive Tax and Tiered Fee Calculator with Exact Cent Rounding | calculate_total_liability | You are to implement a function `calculate_total_liability(income_cents: int, tax_brackets: List[Tuple[int, int]], fee_tiers: List[Tuple[int, int]]) -> int`.
* `income_cents` – non‑negative integer representing the gross income in **cents** (i.e., 1 dollar = 100 cents). 0 ≤ income_cents ≤ 10^12.
* `tax_brackets` – a l... | import decimal
from decimal import Decimal, ROUND_HALF_UP
from typing import List, Tuple
def calculate_total_liability(income_cents: int, tax_brackets: List[Tuple[int, int]], fee_tiers: List[Tuple[int, int]]) -> int:
# Ensure Decimal uses enough precision
decimal.getcontext().prec = 28
total_tax = 0
pr... | from decimal import Decimal, ROUND_HALF_UP
from typing import List, Tuple
def calculate_total_liability(income_cents: int, tax_brackets: List[Tuple[int, int]], fee_tiers: List[Tuple[int, int]]) -> int:
# Calculate tax
total_tax_cents = 0
if tax_brackets:
prev_threshold = 0
for threshold, r... | def check(candidate):
assert candidate(*(123456, [(50000, 1000), (150000, 2000), (300000, 3000)], [(100000, 2500), (200000, 5000), (1000000, 10000)])) == 24691
assert candidate(*(50000, [(50000, 1500), (100000, 2500)], [(60000, 3000)])) == 10500
assert candidate(*(800000, [(200000, 1000), (500000, 2000)], [... | 12 | 11 | 23 | 17 | 32 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04791 | state_machines_and_systems | Vector-clock / Lamport timestamp causality comparator and concurrent event detector | false | medium | Vector Clock Causality Comparator | compare_vector_clocks | Write a function `compare_vector_clocks(vc1: List[int], vc2: List[int]) -> str` that determines the causal relationship between two events described by their vector clocks.
**Definitions**
- A *vector clock* is a list of non‑negative integers of equal length `n`. The i‑th element counts the number of events originated... | def compare_vector_clocks(vc1, vc2):
"""Return the causal relation between two vector clocks.
Args:
vc1 (list[int]): First vector clock.
vc2 (list[int]): Second vector clock.
Returns:
str: One of "happens_before", "happens_after", "concurrent", or "invalid".
"""
if len(vc1)... | def compare_vector_clocks(vc1: list, vc2: list) -> str:
if len(vc1) != len(vc2):
return "invalid"
n = len(vc1)
all_leq = True
any_less = False
for i in range(n):
if vc1[i] > vc2[i]:
all_leq = False
break
if vc1[i] < vc2[i]:
any_le... | def check(candidate):
assert candidate(*([1, 2, 0], [2, 2, 1])) == 'happens_before'
assert candidate(*([2, 2, 1], [1, 2, 0])) == 'happens_after'
assert candidate(*([3, 1], [2, 5])) == 'concurrent'
assert candidate(*([0, 0, 0], [0, 0, 0])) == 'concurrent'
assert candidate(*([1, 2], [1, 2, 3])) == 'in... | 10 | 10 | 20 | 4 | 28 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04789 | business_logic_and_fintech | Progressive tax bracket & tiered fee calculator with exact integer-cent rounding | false | medium-hard | Progressive Tax and Tiered Transaction Fee Calculator | calculate_tax_and_fee | You are to implement a function `calculate_tax_and_fee(income: int, transactions: List[int]) -> dict` that computes two monetary amounts in integer cents:
* **Tax** – a progressive income tax applied to the whole `income` based on predefined brackets.
* **Fee** – a per‑transaction fee that depends on the total number ... | def calculate_tax_and_fee(income: int, transactions: list) -> dict:
# Helper for half‑up rounding of positive numbers
def round_half_up(x: float) -> int:
return int(x + 0.5)
# ----- Tax calculation -----
brackets = [(0, 10_000, 0.0), (10_000, 30_000, 0.10), (30_000, 100_000, 0.20), (100_000, fl... | def calculate_tax_and_fee(income: int, transactions: list) -> dict:
# Calculate tax
tax_dollars = 0.0
if income > 0:
# Bracket 1: 0 - 10000 at 0%
bracket1 = min(income, 10000)
tax_dollars += bracket1 * 0.0
# Bracket 2: 10000 - 30000 at 10%
if income > 10000:
... | def check(candidate):
assert candidate(*(0, [])) == {'tax': 0, 'fee': 0}
assert candidate(*(5000, [100, -50])) == {'tax': 0, 'fee': 200}
assert candidate(*(15000, [])) == {'tax': 50000, 'fee': 0}
assert candidate(*(45000, [200, -50, 300])) == {'tax': 500000, 'fee': 300}
assert candidate(*(250000, []... | 10 | 11 | 21 | 19 | 44 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05395 | binary_search_and_greedy | Two-pointer / prefix-sum subarray bounds with negative numbers and modular constraints | false | medium-hard | Count subarrays with a given modular sum | count_modular_subarrays | Write a function `count_modular_subarrays(arr: List[int], k: int, m: int) -> int` that returns the number of contiguous sub‑arrays (non‑empty) whose element sum modulo `k` equals `m`.
**Definitions**
- A *sub‑array* of `arr` is a slice `arr[l:r]` with `0 \le l < r \le len(arr)`.
- The *sum* of a sub‑array is the ordin... | def count_modular_subarrays(arr, k, m):
"""Return the number of contiguous sub‑arrays whose sum modulo k equals m.
If k <= 0 or m not in [0, k) return -1.
"""
if k <= 0 or not (0 <= m < k):
return -1
from collections import defaultdict
freq = defaultdict(int)
# freq[x] = number of pr... | from typing import List
def count_modular_subarrays(arr: List[int], k: int, m: int) -> int:
# Validate inputs
if not isinstance(k, int) or k <= 0:
return -1
if not isinstance(m, int) or m < 0 or m >= k:
return -1
n = len(arr)
if n == 0:
return 0
# We use the pr... | def check(candidate):
assert candidate(*([3, 1, 4, 1, 5], 5, 3)) == 2
assert candidate(*([-2, -3, 7, 1], 4, 1)) == 3
assert candidate(*([], 10, 0)) == 0
assert candidate(*([], 7, 3)) == 0
assert candidate(*([10], 6, 4)) == 1
assert candidate(*([5], 3, 2)) == 1
assert candidate(*([0, 0, 0], 1... | 14 | 10 | 24 | 8 | 20 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04765 | parsing_and_compilers | Nested bracket/macro template expander with syntax and cycle error handling | false | medium-hard | Nested Macro Template Expander with Cycle Detection | expand_template | You are given a template string `template` and a dictionary `macros` mapping macro names to their replacement strings. A macro invocation in the template is written as `{{NAME}}` where `NAME` consists of one or more uppercase English letters (A‑Z) only. The replacement string may itself contain macro invocations, allow... | import re
from typing import Dict, Set, List
def expand_template(template: str, macros: Dict[str, str]) -> str:
# pre‑compile pattern for a single macro invocation
pattern = re.compile(r"\{\{([A-Z]{1,10})\}\}")
# cache for already fully expanded macros to avoid recomputation
expanded_cache: Dict[str, ... | import re
def expand_template(template: str, macros: dict) -> str:
# Pattern to match macro invocations: {{NAME}} where NAME is 1-10 uppercase letters
macro_pattern = re.compile(r'\{\{([A-Z]{1,10})\}\}')
# We need to simulate the expansion process as described:
# 1. Scan left to right, replace fir... | def check(candidate):
assert candidate(*('Hello, {{NAME}}!', {'NAME': 'Bob'})) == 'Hello, Bob!'
assert candidate(*('{{A}}', {'A': '{{B}}', 'B': '{{C}}', 'C': 'Done'})) == 'Done'
assert candidate(*('Start {{X}} End', {'Y': 'value'})) == 'UNDEFINED'
assert candidate(*('{{A}}', {'A': '{{B}}'})) == 'UNDEFIN... | 14 | 11 | 25 | 20 | 56 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06023 | dynamic_programming | 2D grid DP with obstacles, energy/budget constraints, and exact minimum cost | false | hard | Minimum Cost Path in a Grid with Obstacles and Budget | min_cost_path_with_budget | You are given a rectangular grid `grid` of size `n \times m` (1 \le n, m \le 100). Each element `grid[i][j]` is either:
- a non‑negative integer `c` (0 \le c \le 10^6) representing the energy cost of stepping on cell (i, j), or
- the integer `-1` representing an impassable obstacle.
You start at the top‑left cell (0, 0... | import heapq
from typing import List, Tuple
def min_cost_path_with_budget(grid: List[List[int]], budget: int) -> int:
n = len(grid)
m = len(grid[0]) if n else 0
if n == 0 or m == 0:
return -1
# start and end are guaranteed not obstacles per statement
start_cost = grid[0][0]
if start_cos... | from typing import List
import heapq
def min_cost_path_with_budget(grid: List[List[int]], budget: int) -> int:
n = len(grid)
m = len(grid[0])
# Check if start or end is obstacle (though problem guarantees they are not)
if grid[0][0] == -1 or grid[n-1][m-1] == -1:
return -1
# If bu... | def check(candidate):
assert candidate(*([[1, 2, 3], [4, -1, 5], [6, 7, 8]], 20)) == 19
assert candidate(*([[0, -1], [5, 0]], 4)) == -1
assert candidate(*([[2, 2], [2, 2]], 8)) == 6
assert candidate(*([[1, 3, 1, 2], [2, -1, 2, 1], [4, 2, 1, 3], [1, 1, 1, 1]], 12)) == 10
assert candidate(*([[5, 1], [... | 13 | 11 | 24 | 12 | 34 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05561 | state_machines_and_systems | Vector-clock / Lamport timestamp causality comparator and concurrent event detector | false | hard | Vector Clock Causality Comparator | compare_vector_clocks | You are given two *vector clocks* that represent the logical timestamps of two events in a distributed system. A vector clock is expressed as a JSON object (Python ``dict``) that maps a process identifier (a non‑empty string consisting of only ASCII letters and digits) to a non‑negative integer counter. All processes t... | def compare_vector_clocks(a, b):
# Validate inputs
if not isinstance(a, dict) or not isinstance(b, dict):
return "invalid"
# Helper to validate a single clock
def valid_clock(clk):
for k, v in clk.items():
if not isinstance(k, str) or not k:
return False
... | def compare_vector_clocks(a: dict, b: dict) -> str:
# Validate inputs
if not isinstance(a, dict) or not isinstance(b, dict):
return "invalid"
# Validate keys and values for a
for key, value in a.items():
if not isinstance(key, str) or len(key) == 0:
return "invalid"
... | def check(candidate):
assert candidate(*({'p1': 1, 'p2': 2}, {'p1': 1, 'p2': 3})) == 'a<b'
assert candidate(*({'p1': 4, 'p2': 5}, {'p1': 2, 'p2': 5})) == 'a>b'
assert candidate(*({'p1': 3}, {'p2': 3})) == 'concurrent'
assert candidate(*({'p1': 0, 'p2': 0}, {'p1': 0, 'p2': 0})) == 'concurrent'
assert... | 14 | 10 | 24 | 4 | 40 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02281 | state_machines_and_systems | Consistent hashing ring simulator (sorted ring positions, key migration count on node changes) | false | medium-hard | Consistent Hashing Ring Migration Counter | count_key_migrations | You are given a simplified consistent‑hashing ring.
* The ring has a fixed size **M = 360** (positions are integers from 0 to 359 inclusive, and the ring wraps around).
* There are initially **N** distinct nodes placed at integer positions `nodes[i]` (0 ≤ nodes[i] < 360). The list `nodes` is given in arbitrary order a... | import bisect
from typing import List, Tuple
def _owner_for_key(key: int, sorted_nodes: List[int]) -> int:
"""Return the position of the node that owns *key* given a sorted list of node positions.
The ring size is 360.
"""
# Find the first node with position >= key
idx = bisect.bisect_left(sorted_n... | from typing import List, Tuple
def count_key_migrations(nodes: List[int], keys: List[int], operations: List[Tuple[str, int]]) -> List[int]:
"""
Count the number of keys that change their owner after each operation.
"""
# Make a working copy of nodes to avoid mutating input
current_nodes = sorted(no... | def check(candidate):
assert candidate(*([0, 120, 240], [10, 130, 250], [('add', 60)])) == [1]
assert candidate(*([0, 180], [90, 270], [('remove', 0), ('add', 45)])) == [1, 1]
assert candidate(*([0, 180], [10, 20, 30, 170, 190, 350], [('add', 15)])) == [1]
assert candidate(*([0, 120, 240], [5, 125, 245]... | 12 | 10 | 22 | 10 | 42 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04402 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | medium-hard | Lexicographically Smallest Topological Order and Critical Path Duration in a DAG | schedule_tasks | You are given a directed acyclic graph (DAG) that represents a set of tasks and their precedence constraints.
**Function signature**
```python
def schedule_tasks(tasks: List[Dict[str, Any]], dependencies: List[List[str]]) -> Dict[str, Any]:
```
* `tasks` – a list of dictionaries, each describing a single task. Every ... | import heapq
from typing import List, Dict, Any
def schedule_tasks(tasks: List[Dict[str, Any]], dependencies: List[List[str]]) -> Dict[str, Any]:
# Build adjacency list and indegree map
adj: Dict[str, List[str]] = {}
indeg: Dict[str, int] = {}
duration: Dict[str, int] = {}
for t in tasks:
t... | import heapq
from collections import defaultdict, deque
from typing import List, Dict, Any
def schedule_tasks(tasks: List[Dict[str, Any]], dependencies: List[List[str]]) -> Dict[str, Any]:
# Build a mapping from task id to duration
task_durations = {}
task_ids = set()
for task in tasks:
tid = t... | def check(candidate):
assert candidate(*([{'id': 'a', 'duration': 10}], [])) == {'order': ['a'], 'critical_path': 10}
assert candidate(*([{'id': 'b', 'duration': 2}, {'id': 'a', 'duration': 3}], [])) == {'order': ['a', 'b'], 'critical_path': 3}
assert candidate(*([{'id': 'a', 'duration': 1}, {'id': 'b', 'du... | 11 | 11 | 22 | 18 | 40 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02588 | math_and_combinatorics | 2D integer computational geometry (convex hull, doubled polygon area, segment intersection) | false | hard | Count Lattice Points Strictly Inside the Convex Hull | count_lattice_points_inside_hull | You are to implement a function with the exact signature:
```python
def count_lattice_points_inside_hull(points: List[Tuple[int, int]]) -> int:
```
`points` is a list of distinct integer-coordinate points in the 2‑dimensional plane. The list may be empty, contain a single point, or any number of points up to 10⁵. Eac... | from typing import List, Tuple
from math import gcd
def _cross(o: Tuple[int, int], a: Tuple[int, int], b: Tuple[int, int]) -> int:
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def _convex_hull(points: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
# Monotone chain algorithm, returns ... | import math
from typing import List, Tuple
def _cross(o: Tuple[int, int], a: Tuple[int, int], b: Tuple[int, int]) -> int:
"""Returns the cross product of vectors OA and OB."""
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def _dist_sq(p1: Tuple[int, int], p2: Tuple[int, int]) -> int:
... | def check(candidate):
assert candidate(*([],)) == 0
assert candidate(*([(0, 0)],)) == 0
assert candidate(*([(0, 0), (1, 0)],)) == 0
assert candidate(*([(0, 0), (2, 0), (0, 2)],)) == 0
assert candidate(*([(0, 0), (4, 0), (0, 3)],)) == 3
assert candidate(*([(0, 0), (2, 0), (1, 1), (0, 2), (2, 2)],... | 14 | 8 | 22 | 9 | 49 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02242 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | medium-hard | Lexicographically Smallest Topological Order and Critical Path Length in a DAG | dag_critical_path | You are given a directed acyclic graph (DAG) that represents a set of tasks and precedence constraints. Each task i (0-indexed) has a non‑negative integer duration d[i]. The graph is described by a list of directed edges `edges`, where each edge is a two‑element list `[u, v]` meaning task `u` must finish before task `v... | import heapq
from typing import List, Tuple, Optional
def dag_critical_path(n: int, edges: List[List[int]], durations: List[int]) -> Tuple[Optional[List[int]], Optional[int]]:
# Build adjacency list and indegree count
adj = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
adj[u].append... | from typing import List, Tuple, Optional
import heapq
def dag_critical_path(n: int, edges: List[List[int]], durations: List[int]) -> Tuple[Optional[List[int]], Optional[int]]:
# Build adjacency list and compute indegrees
adj = [[] for _ in range(n)]
indegree = [0] * n
for edge in edges:
u,... | def check(candidate):
assert candidate(*(3, [[0, 1], [1, 2]], [1, 2, 3])) == ([0, 1, 2], 6)
assert candidate(*(5, [[0, 1], [0, 2], [1, 3], [2, 3], [3, 4]], [2, 3, 5, 4, 1])) == ([0, 1, 2, 3, 4], 12)
assert candidate(*(4, [[1, 2]], [4, 1, 2, 3])) == ([0, 1, 2, 3], 4)
assert candidate(*(4, [[2, 3]], [0, 0... | 10 | 11 | 21 | 19 | 47 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07394 | strings_and_text_processing | Fuzzy string search, k-mismatch pattern finder, and palindrome partitioning | false | hard | Fuzzy Palindromic Pattern Finder | find_fuzzy_palindromic_occurrences | Write a function `find_fuzzy_palindromic_occurrences(text: str, pattern: str, k: int) -> List[int]` that returns a list of all starting indices `i` (0‑based) such that:
1. The substring `sub = text[i:i+m]` where `m = len(pattern)` is fully contained in `text` (i.e., `i + m <= len(text)`).
2. The Hamming distance betwe... | def find_fuzzy_palindromic_occurrences(text: str, pattern: str, k: int):
"""Return all start indices where the substring of length len(pattern)
is a palindrome and differs from pattern in at most k positions.
"""
n = len(text)
m = len(pattern)
if m > n:
return []
# clamp k to m
i... | def find_fuzzy_palindromic_occurrences(text: str, pattern: str, k: int) -> list:
n = len(text)
m = len(pattern)
# If pattern is longer than text, no occurrences possible
if m > n:
return []
# Clamp k to m
if k > m:
k = m
results = []
# Precompute palin... | def check(candidate):
assert candidate(*('abacaba', 'aba', 0)) == [0, 4]
assert candidate(*('abacaba', 'aba', 1)) == [0, 2, 4]
assert candidate(*('aaaaa', 'aaa', 0)) == [0, 1, 2]
assert candidate(*('abcde', 'fgh', 3)) == []
assert candidate(*('racecar', 'racecar', 0)) == [0]
assert candidate(*('... | 14 | 9 | 23 | 7 | 38 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04456 | strings_and_text_processing | Fuzzy string search, k-mismatch pattern finder, and palindrome partitioning | false | medium-hard | Minimum Palindrome Partitioning with Limited Character Changes | min_pal_partition_with_k_changes | Write a function `min_pal_partition_with_k_changes(s: str, k: int) -> int` that computes the smallest possible number of substrings the input string `s` can be split into so that each substring is a palindrome **after performing at most `k` character modifications in total**. A modification changes any single character... | def min_pal_partition_with_k_changes(s: str, k: int) -> int:
n = len(s)
# cost[i][j]: min changes to make s[i:j+1] a palindrome
cost = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if s[i] == s[j]:
... | def min_pal_partition_with_k_changes(s: str, k: int) -> int:
n = len(s)
if n == 0:
return 0
# Precompute cost[i][j]: min changes to make s[i:j+1] a palindrome
cost = [[0] * n for _ in range(n)]
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i... | def check(candidate):
assert candidate(*('abca', 1)) == 1
assert candidate(*('racecar', 0)) == 1
assert candidate(*('abcde', 0)) == 5
assert candidate(*('abcde', 2)) == 1
assert candidate(*('a', 0)) == 1
assert candidate(*('aaabbb', 3)) == 1
assert candidate(*('abcd', 1)) == 2
assert can... | 14 | 8 | 22 | 4 | 28 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02382 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | medium | Lexicographically Smallest Topological Order and Critical Path Length | schedule_tasks | You are given a directed acyclic graph (DAG) that models a set of tasks and precedence constraints.
**Function signature**
```python
def schedule_tasks(tasks: dict[str, int], dependencies: list[list[str]]) -> dict[str, object]:
```
- `tasks` maps each task identifier (a non‑empty string consisting of only lowercase En... | import collections
import heapq
from typing import Dict, List, Tuple, Any
def schedule_tasks(tasks: Dict[str, int], dependencies: List[List[str]]) -> Dict[str, Any]:
# Build adjacency list and indegree map
adj: Dict[str, List[str]] = {node: [] for node in tasks}
indeg: Dict[str, int] = {node: 0 for node in... | import heapq
from collections import defaultdict, deque
def schedule_tasks(tasks: dict[str, int], dependencies: list[list[str]]) -> dict[str, object]:
# Build adjacency list and in-degree count
graph = defaultdict(list)
in_degree = defaultdict(int)
all_nodes = set(tasks.keys())
for pre, post i... | def check(candidate):
assert candidate(*({'a': 1}, [])) == {'order': ['a'], 'critical_path': 1}
assert candidate(*({'a': 2, 'b': 3, 'c': 5}, [['a', 'b'], ['b', 'c']])) == {'order': ['a', 'b', 'c'], 'critical_path': 10}
assert candidate(*({'a': 1, 'b': 2, 'c': 2, 'd': 1}, [['a', 'b'], ['a', 'c']])) == {'orde... | 12 | 12 | 24 | 19 | 39 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-08169 | business_logic_and_fintech | Progressive tax bracket & tiered fee calculator with exact integer-cent rounding | false | medium | Progressive Tax Bracket with Tiered Fees (cent‑exact) | calculate_total_tax | You are to implement a function `calculate_total_tax(income: int, brackets: List[Dict[str, int]]) -> int`.
**Function signature**
```python
def calculate_total_tax(income: int, brackets: List[Dict[str, int]]) -> int:
```
**Parameters**
- `income`: a non‑negative integer representing the yearly gross income in **dolla... | import math
from typing import List, Dict
def calculate_total_tax(income: int, brackets: List[Dict[str, int]]) -> int:
# Edge cases
if income <= 0 or not brackets:
return 0
# Sort brackets by up_to
sorted_brackets = sorted(brackets, key=lambda b: b["up_to"])
total_cents = 0
prev_up = 0
... | def calculate_total_tax(income: int, brackets: list) -> int:
if not brackets or income == 0:
return 0
# Sort brackets by up_to value
sorted_brackets = sorted(brackets, key=lambda b: b['up_to'])
total_cents = 0
previous_up_to = 0
for b in sorted_brackets:
up_to = b[... | def check(candidate):
assert candidate(*(120000, [{'up_to': 50000, 'rate': 1000, 'fee': 5000}, {'up_to': 100000, 'rate': 2000, 'fee': 3000}, {'up_to': 150000, 'rate': 3000, 'fee': 2000}])) == 2110000
assert candidate(*(50000, [{'up_to': 50000, 'rate': 1500, 'fee': 2500}, {'up_to': 100000, 'rate': 2500, 'fee': 3... | 12 | 13 | 25 | 18 | 31 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03252 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | medium | Lexicographically Smallest Topological Order and Critical Path in a DAG | schedule_dag | You are given a directed acyclic graph (DAG) that represents a set of tasks and their prerequisite relationships.
**Function signature**
```python
def schedule_dag(tasks: dict[str, int], edges: list[list[str]]) -> dict:
```
- `tasks` maps a **task identifier** (a non‑empty string consisting of only alphanumeric charac... | import collections
import heapq
def schedule_dag(tasks, edges):
# Build graph
adj = {node: [] for node in tasks}
indeg = {node: 0 for node in tasks}
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
# Detect cycle using Kahn's algorithm while also producing lexicographically smalles... | import heapq
from collections import defaultdict, deque
def schedule_dag(tasks: dict[str, int], edges: list[list[str]]) -> dict:
# Build adjacency list and in-degree count
graph = defaultdict(list)
in_degree = defaultdict(int)
all_nodes = set(tasks.keys())
for u, v in edges:
graph[u].a... | def check(candidate):
assert candidate(*({'a': 3, 'b': 2, 'c': 4, 'd': 1}, [['a', 'c'], ['b', 'c'], ['c', 'd']])) == {'order': ['a', 'b', 'c', 'd'], 'critical_path': 8}
assert candidate(*({'x': 5, 'y': 6}, [])) == {'order': ['x', 'y'], 'critical_path': 6}
assert candidate(*({'solo': 10}, [])) == {'order': [... | 10 | 12 | 22 | 19 | 31 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02622 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | medium | Lexicographically Smallest Topological Order and Critical Path Length in a DAG | dag_schedule | You are given a directed acyclic graph (DAG) representing task dependencies. Each node is a distinct task identified by a positive integer ID. Every task i has an execution duration given by durations[i] (a positive integer). An edge (u, v) means task u must finish before task v can start.
Write a function with the ex... | import heapq
from typing import List, Dict, Any
def dag_schedule(edges: List[List[int]], durations: Dict[int, int]) -> Dict[str, Any]:
# Build adjacency list and indegree map
adj: Dict[int, List[int]] = {node: [] for node in durations}
indegree: Dict[int, int] = {node: 0 for node in durations}
seen_edg... | import heapq
from typing import List, Dict, Any
def dag_schedule(edges: List[List[int]], durations: Dict[int, int]) -> Dict[str, Any]:
if not durations:
return {"order": [], "critical_path": 0}
# Collect all task IDs
all_tasks = set(durations.keys())
# Build adjacency list and in-degr... | def check(candidate):
assert candidate(*([[1, 3], [2, 3]], {1: 3, 2: 2, 3: 4})) == {'order': [1, 2, 3], 'critical_path': 7}
assert candidate(*([], {42: 7})) == {'order': [42], 'critical_path': 7}
assert candidate(*([[5, 6]], {5: 2, 6: 3, 7: 1, 8: 4})) == {'order': [5, 6, 7, 8], 'critical_path': 5}
asser... | 10 | 9 | 19 | 17 | 40 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02657 | binary_search_and_greedy | Parametric binary search on answer (minimize max load, shipping capacity, bandwidth allocation) | false | hard | Minimize Maximum Load with Contiguous Assignment | min_max_load | You are given a list of positive integers `tasks` where `tasks[i]` denotes the processing time of the i-th task, and an integer `k` representing the number of identical workers. Each worker must be assigned a **contiguous** subsequence of tasks (the order of tasks cannot be changed). Every task must be assigned to exac... | def min_max_load(tasks, k):
# Edge case: not enough tasks for workers
n = len(tasks)
if k > n:
return -1
# Helper: can we partition into <= k groups with max sum <= limit?
def feasible(limit: int) -> bool:
groups = 1
current = 0
for t in tasks:
if t > lim... | def min_max_load(tasks: list[int], k: int) -> int:
n = len(tasks)
if k > n:
return -1
if k == 0:
# k >= 1 per constraints, but handle gracefully
return -1
# Binary search on the answer
# Lower bound: max(tasks) because each worker must handle at least one task
# Uppe... | def check(candidate):
assert candidate(*([7, 2, 5, 10, 8], 2)) == 18
assert candidate(*([1, 2, 3, 4, 5], 3)) == 6
assert candidate(*([10, 20, 30], 3)) == 30
assert candidate(*([4, 9, 1, 7], 1)) == 21
assert candidate(*([5, 6], 3)) == -1
assert candidate(*([5, 5, 5, 5, 5, 5], 4)) == 10
assert... | 12 | 10 | 22 | 18 | 31 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03717 | binary_search_and_greedy | Greedy resource allocation, task cooldown scheduling, and circular tour feasibility | false | medium | Maximum Profit with Task Type Cooldown | max_profit | You are given a list of tasks and an integer cooldown `k`.
Each task is represented as a two‑element list `[profit, type]` where:
- `profit` is a positive integer (1 ≤ profit ≤ 10^9) denoting the profit earned by performing this task.
- `type` is a string consisting of 1‑10 lowercase English letters identifying the ta... | import heapq
from typing import List, Union
def max_profit(tasks: List[List[Union[int, str]]], k: int) -> int:
# Group tasks by type and sort each group's profits descending
type_to_profits = {}
for profit, typ in tasks:
type_to_profits.setdefault(typ, []).append(profit)
for typ in type_to_prof... | from typing import List, Union
import heapq
from collections import defaultdict
def max_profit(tasks: List[List[Union[int, str]]], k: int) -> int:
if not tasks:
return 0
# Group tasks by type, and for each type, sort profits in descending order
# We'll use a max-heap for each type to efficient... | def check(candidate):
assert candidate(*([[5, 'a'], [3, 'b'], [8, 'a'], [2, 'c']], 2)) == 18
assert candidate(*([[10, 'x'], [10, 'y'], [10, 'z']], 0)) == 30
assert candidate(*([[42, 'solo']], 5)) == 42
assert candidate(*([], 3)) == 0
assert candidate(*([[4, 'a'], [7, 'a'], [5, 'a']], 1)) == 16
a... | 10 | 12 | 22 | 14 | 51 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05289 | business_logic_and_fintech | Prorated SaaS subscription billing, mid-cycle tier upgrades, and exact integer-cent ledger | false | medium | Prorated SaaS Subscription Upgrade Billing | calculate_prorated_charge | You are to implement a function `calculate_prorated_charge(current_plan, new_plan, days_used, days_in_cycle)` that computes the exact integer‑cent ledger entries when a SaaS customer upgrades their subscription tier in the middle of a billing cycle.
**Parameters**
- `current_plan`: a dict with two keys:
- `'tier'`... | def calculate_prorated_charge(current_plan, new_plan, days_used, days_in_cycle):
# Guard for completed cycle
if days_used >= days_in_cycle:
return {'credit_cents': 0, 'charge_cents': 0, 'total_due_cents': 0}
remaining = days_in_cycle - days_used
cur_price = current_plan['monthly_price_cents']
... | def calculate_prorated_charge(current_plan, new_plan, days_used, days_in_cycle):
if days_used == days_in_cycle:
return {
'credit_cents': 0,
'charge_cents': 0,
'total_due_cents': 0
}
remaining = days_in_cycle - days_used
current_price = current_plan['m... | def check(candidate):
assert candidate(*({'tier': 'basic', 'monthly_price_cents': 1000}, {'tier': 'pro', 'monthly_price_cents': 2500}, 10, 30)) == {'credit_cents': 666, 'charge_cents': 1666, 'total_due_cents': 1000}
assert candidate(*({'tier': 'basic', 'monthly_price_cents': 1000}, {'tier': 'pro', 'monthly_pric... | 10 | 10 | 20 | 18 | 19 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03336 | strings_and_text_processing | Fuzzy string search, k-mismatch pattern finder, and palindrome partitioning | false | medium | K‑mismatch pattern finder with palindrome partition metric | k_mismatch_pal_partition_counts | You are to implement a function with the exact signature:
```python
def k_mismatch_pal_partition_counts(text: str, pattern: str, k: int) -> List[int]:
```
The function must perform the following steps:
1. **Sliding window search** – Consider every substring `window` of `text` whose length equals `len(pattern)`. The win... | def k_mismatch_pal_partition_counts(text: str, pattern: str, k: int):
# Helper: compute minimal palindrome partition count for a given string s
def min_pal_partitions(s: str) -> int:
n = len(s)
# pal[i][j] = True if s[i:j+1] is a palindrome
pal = [[False] * n for _ in range(n)]
f... | from typing import List
def k_mismatch_pal_partition_counts(text: str, pattern: str, k: int) -> List[int]:
"""
Returns a list of minimum palindrome partition counts for every window in text
of length len(pattern) that has at most k mismatches with pattern.
"""
n = len(text)
m = len(pattern)
... | def check(candidate):
assert candidate(*('abacaba', 'aba', 0)) == [1, 1]
assert candidate(*('abcde', 'abf', 1)) == [3]
assert candidate(*('aaaaa', 'aaa', 0)) == [1, 1, 1]
assert candidate(*('abcdef', 'xyz', 3)) == [3, 3, 3, 3]
assert candidate(*('abcd', 'abcd', 0)) == [4]
assert candidate(*('rac... | 14 | 11 | 25 | 11 | 29 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06567 | binary_search_and_greedy | Multi-server priority queue / load-balancer deterministic event simulation | false | medium | Deterministic Multi‑Server Load Balancer Simulation | simulate_load_balancer | You are given a list of `servers` and a list of `tasks`.
* `servers` is a list of positive integers `c[0], c[1], ..., c[m-1]` where `c[i]` is the *capacity* of server `i`. All servers are initially idle.
* `tasks` is a list of triples `(t, d, p)` ordered by non‑decreasing arrival time `t` (i.e. `tasks[i][0] <= tasks[i... | import heapq
from typing import List, Tuple
def simulate_load_balancer(servers: List[int], tasks: List[Tuple[int, int, int]]) -> List[int]:
if not tasks:
return []
# Prepare a heap of idle servers ordered by (-capacity, index)
idle_heap = [(-c, i) for i, c in enumerate(servers)]
heapq.heapify(i... | import heapq
from typing import List, Tuple
def simulate_load_balancer(servers: List[int], tasks: List[Tuple[int, int, int]]) -> List[int]:
if not tasks:
return []
m = len(servers)
n = len(tasks)
# We need to efficiently find the idle server with largest capacity, then smallest index.... | def check(candidate):
assert candidate(*([10], [(0, 5, 1), (5, 3, 2), (8, 2, 3)])) == [0, 0, 0]
assert candidate(*([2, 2, 2], [(0, 5, 1), (0, 3, 2), (0, 1, 3)])) == [0, 1, 2]
assert candidate(*([5, 3], [(0, 4, 10), (1, 2, 5), (2, 1, 1), (3, 1, 2)])) == [0, 1, -1, 1]
assert candidate(*([4, 6], [(0, 3, 1)... | 14 | 12 | 26 | 16 | 27 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02432 | graph_and_network_algorithms | Minimum spanning tree / network clustering with mandatory or forbidden edges | false | hard | MST with Mandatory and Forbidden Edges | minimum_spanning_cluster | You are given an undirected weighted graph with vertices numbered from 1 to n. The graph is described by three inputs:
* `n` – an integer (1 ≤ n ≤ 10⁴) – the number of vertices.
* `edges` – a list of tuples `(u, v, w)` where `u` and `v` are distinct vertex numbers (1‑based) and `w` is a positive integer weight (1 ≤ w ... | from typing import List, Tuple
def minimum_spanning_cluster(n: int,
edges: List[Tuple[int, int, int]],
mandatory: List[Tuple[int, int]],
forbidden: List[Tuple[int, int]]) -> int:
# Helper: DSU
class DSU:
__slots__ = ("p... | from typing import List, Tuple
def minimum_spanning_cluster(n: int,
edges: List[Tuple[int, int, int]],
mandatory: List[Tuple[int, int]],
forbidden: List[Tuple[int, int]]) -> int:
# Build a set of forbidden edges for O(1) lookup
... | def check(candidate):
assert candidate(*(1, [], [], [])) == 0
assert candidate(*(2, [(1, 2, 5)], [(1, 2)], [])) == 5
assert candidate(*(2, [], [(1, 2)], [])) == -1
assert candidate(*(3, [(1, 2, 3), (2, 3, 4)], [(1, 2)], [(1, 2)])) == -1
assert candidate(*(3, [(1, 2, 1), (2, 3, 1), (1, 3, 10)], [(1, ... | 13 | 8 | 21 | 9 | 88 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07914 | strings_and_text_processing | Custom tokenization, run-length / LZ-style lossless compression and decompression | false | medium | Run‑Length Encoding with Bracketed Counts | encode_run_length | You are to implement a loss‑less run‑length encoder for ASCII strings.
**Function signature**
```python
def encode_run_length(text: str) -> str:
```
**Encoding rules**
1. The input `text` consists only of printable ASCII characters (code points 32‑126). It may be empty.
2. Scan the string from left to right, grouping... | def encode_run_length(text: str) -> str:
# Edge case: empty input
if not text:
return ""
# Use a list for efficient concatenation
result_chars = []
i = 0
n = len(text)
while i < n:
ch = text[i]
# Count run length
j = i + 1
while j < n and text[j] == ch... | def encode_run_length(text: str) -> str:
if not text:
return ""
result = []
n = len(text)
i = 0
while i < n:
current_char = text[i]
count = 1
# Count the length of the current run
while i + count < n and text[i + count] == current_char:
... | def check(candidate):
assert candidate(*('',)) == ''
assert candidate(*('a',)) == 'a'
assert candidate(*('aa',)) == 'a[2]'
assert candidate(*('aaa',)) == 'a[3]'
assert candidate(*('aaaa',)) == 'a[4]'
assert candidate(*('ab',)) == 'ab'
assert candidate(*('aaabbb',)) == 'a[3]b[3]'
assert c... | 13 | 4 | 17 | 16 | 21 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05276 | strings_and_text_processing | Minimal line diff / longest common substring and alignment scoring | false | hard | Maximum Alignment Score with Custom Scoring | max_alignment_score | You are given two strings `s` and `t` consisting only of uppercase English letters (A‑Z). You are also given three integers `match`, `mismatch` and `gap` (they can be negative, zero or positive).\n\nDefine an alignment of `s` and `t` as a pair of strings `(s', t')` of equal length obtained by inserting any number (incl... | def max_alignment_score(s: str, t: str, match: int, mismatch: int, gap: int) -> int:
n, m = len(s), len(t)
# dp[i][j] = best score for suffix s[i:], t[j:]
# We use only two rows to save memory.
prev = [0] * (m + 1)
# base case: i == n
for j in range(m - 1, -1, -1):
prev[j] = prev[j + 1] ... | def max_alignment_score(s: str, t: str, match: int, mismatch: int, gap: int) -> int:
n = len(s)
m = len(t)
# Initialize DP table with a very small number
# dp[i][j] represents the max score for aligning s[:i] and t[:j]
# We use -infinity for initialization
NEG_INF = float('-inf')
d... | def check(candidate):
assert candidate(*('', '', 1, -1, -2)) == 0
assert candidate(*('A', '', 5, -3, -2)) == -2
assert candidate(*('', 'BC', 5, -3, -2)) == -4
assert candidate(*('AGT', 'AG', 2, -1, -2)) == 2
assert candidate(*('ABC', 'DEF', 5, -3, -2)) == -9
assert candidate(*('AAAA', 'AA', 3, -... | 12 | 9 | 21 | 14 | 22 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07903 | dynamic_programming | Knapsack variants (bounded, subset partitioning, minimum coin/item combination with tie-break) | false | medium-hard | Minimum Weight Subset for Exact Value with Tie‑Breakers | min_weight_subset | You are given a list of `items`, where each item is a dictionary with three keys: `"weight"` (a non‑negative integer), `"value"` (a non‑negative integer), and `"id"` (a unique non‑negative integer identifier). You are also given a target integer `target_value`.
Write a function `min_weight_subset(items: List[Dict[str,... | def min_weight_subset(items, target_value):
# DP over value: for each achievable value store (total_weight, item_count, sorted_ids_tuple)
# Initialize with value 0
INF = 10**18
dp = [(INF, INF, ()) for _ in range(target_value + 1)]
dp[0] = (0, 0, ())
# Process items one by one
for item in it... | def min_weight_subset(items: list, target_value: int) -> list:
n = len(items)
if target_value == 0:
return []
if n == 0:
return []
# DP state: dp[v] = (min_weight, min_count, sorted_ids_tuple)
# We use a dictionary or array indexed by value from 0 to target_value
# Initializ... | def check(candidate):
assert candidate(*([{'id': 5, 'weight': 3, 'value': 4}, {'id': 2, 'weight': 2, 'value': 4}, {'id': 7, 'weight': 5, 'value': 6}], 8)) == [2, 5]
assert candidate(*([{'id': 1, 'weight': 5, 'value': 3}, {'id': 2, 'weight': 5, 'value': 3}, {'id': 3, 'weight': 9, 'value': 6}], 6)) == [3]
ass... | 10 | 11 | 21 | 9 | 36 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07183 | dynamic_programming | Interval scheduling, weighted job partitioning, and non-overlapping segment optimization | false | medium-hard | Maximum Weight of Non‑Overlapping Jobs | max_weight_nonoverlapping_jobs | You are given a list of jobs. Each job is represented as a three‑element list [start, end, weight] where:
- start and end are non‑negative integers with start < end,
- weight is a positive integer representing the profit earned by performing the job.
A set of jobs is **compatible** if no two jobs overlap, i.e. for any ... | def max_weight_nonoverlapping_jobs(jobs):
if not jobs:
return 0
# Convert each job to a tuple for sorting
jobs = [(s, e, w) for s, e, w in jobs]
# Sort by end time
jobs.sort(key=lambda x: x[1])
# Extract end times for binary search
ends = [e for _, e, _ in jobs]
import bisect
... | import bisect
from typing import List
def max_weight_nonoverlapping_jobs(jobs: List[List[int]]) -> int:
if not jobs:
return 0
# Sort jobs by end time
sorted_jobs = sorted(jobs, key=lambda x: x[1])
n = len(sorted_jobs)
# dp[i] = max weight using a subset of the first i jobs (1... | def check(candidate):
assert candidate(*([],)) == 0
assert candidate(*([[0, 1, 10]],)) == 10
assert candidate(*([[1, 3, 5], [2, 5, 6], [4, 6, 5], [6, 7, 4]],)) == 14
assert candidate(*([[0, 2, 3], [2, 4, 5], [4, 6, 4], [6, 8, 2]],)) == 14
assert candidate(*([[0, 3, 5], [3, 5, 6], [5, 9, 7], [1, 4, 4... | 13 | 10 | 23 | 13 | 20 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07226 | strings_and_text_processing | Minimal line diff / longest common substring and alignment scoring | false | hard | Best Scoring Longest Common Substring | find_best_common_substring | Write a function `find_best_common_substring(s1: str, s2: str) -> dict` that examines two input strings `s1` and `s2` (each consisting of ASCII printable characters, length 0 ≤ len ≤ 5000) and returns a dictionary with two keys:
- `"substring"` – the longest substring that appears in **both** strings.
- `"score"` – an ... | def find_best_common_substring(s1: str, s2: str) -> dict:
n, m = len(s1), len(s2)
if n == 0 or m == 0:
return {"substring": "", "score": 0}
# Ensure we iterate over the shorter string for memory efficiency
if n < m:
short, long = s1, s2
rev = False
else:
short, long =... | def find_best_common_substring(s1: str, s2: str) -> dict:
n = len(s1)
m = len(s2)
if n == 0 or m == 0:
return {"substring": "", "score": 0}
# We need to find the longest common substring(s), then among those,
# the one with the highest alignment score, then lexicographically smalle... | def check(candidate):
assert candidate(*('ababc', 'babca')) == {'substring': 'babc', 'score': 24}
assert candidate(*('xyz', 'abc')) == {'substring': '', 'score': 0}
assert candidate(*('aaaa', 'aa')) == {'substring': 'aa', 'score': 10}
assert candidate(*('abcde', 'cdeab')) == {'substring': 'cde', 'score'... | 12 | 8 | 20 | 12 | 75 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03873 | dynamic_programming | 2D grid DP with obstacles, energy/budget constraints, and exact minimum cost | false | medium | Minimum Cost Path with Obstacles and Budget | min_energy_path | You are given a rectangular grid `grid` of size `m × n` (where `1 ≤ m, n ≤ 100`). Each element `grid[i][j]` is either a non‑negative integer representing the energy cost to step onto cell `(i, j)`, or the integer `-1` which denotes an impassable obstacle. You start at the top‑left cell `(0, 0)` and must reach the botto... | import heapq
from typing import List, Tuple
def min_energy_path(grid: List[List[int]], budget: int) -> int:
m, n = len(grid), len(grid[0])
# Dijkstra's algorithm: state = (accumulated_cost, x, y)
INF = 10**18
dist = [[INF] * n for _ in range(m)]
start_cost = grid[0][0]
if start_cost > budget:
... | from typing import List
import heapq
def min_energy_path(grid: List[List[int]], budget: int) -> int:
m = len(grid)
n = len(grid[0])
# If start or end is obstacle (shouldn't happen per constraints, but safety)
if grid[0][0] == -1 or grid[m-1][n-1] == -1:
return -1
# Dijkstra's algo... | def check(candidate):
assert candidate(*([[5]], 5)) == 5
assert candidate(*([[5]], 4)) == -1
assert candidate(*([[1, 2], [3, 4]], 10)) == 7
assert candidate(*([[1, -1], [2, 3]], 7)) == 6
assert candidate(*([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 15)) == -1
assert candidate(*([[1, 3, 1, 2], [2, -1, 2,... | 12 | 10 | 22 | 9 | 31 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02437 | binary_search_and_greedy | Two-pointer / prefix-sum subarray bounds with negative numbers and modular constraints | false | medium-hard | Count bounded-modulo subarrays with negatives | count_modular_subarrays | Write a function `count_modular_subarrays(nums: List[int], mod: int, target: int, min_len: int, max_len: int) -> int` that returns the number of contiguous subarrays of `nums` whose length is between `min_len` and `max_len` (inclusive) **and** whose sum modulo `mod` equals `target`.
**Definitions**
- A *subarray* is a... | import bisect
from collections import defaultdict
from typing import List
def count_modular_subarrays(nums: List[int], mod: int, target: int, min_len: int, max_len: int) -> int:
n = len(nums)
# prefix sums modulo mod
pref = [0] * (n + 1)
cur = 0
for i, v in enumerate(nums, 1):
cur += v
... | from typing import List
from collections import defaultdict
def count_modular_subarrays(nums: List[int], mod: int, target: int, min_len: int, max_len: int) -> int:
n = len(nums)
if n == 0:
return 0
# Compute prefix sums modulo mod
# prefix[0] = 0
# prefix[i] = (nums[0] + ... + nums[i-1... | def check(candidate):
assert candidate(*([3, -1, 4, -2, 2], 5, 3, 2, 4)) == 2
assert candidate(*([0, 0, 0], 1, 0, 1, 3)) == 6
assert candidate(*([7], 10, 7, 1, 1)) == 1
assert candidate(*([-5, 2, -3, 6], 4, 1, 1, 3)) == 3
assert candidate(*([2, 2, 2, 2, 2, 2, 2, 2, 2, 2], 3, 2, 2, 5)) == 7
asser... | 10 | 11 | 21 | 9 | 36 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07070 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | hard | Lexicographically Minimal Topological Order and Critical Path Duration | schedule_dag | You are given a directed acyclic graph (DAG) representing a set of tasks.
Each task is identified by a **unique non‑empty string label** consisting of only ASCII letters `a‑z` and `A‑Z` (case‑sensitive). Every task has a **positive integer duration** (in minutes).
The graph is described by three arguments:
1. `tasks... | import heapq
from typing import List, Dict, Tuple
def schedule_dag(tasks: List[str], duration: Dict[str, int], precedence: List[List[str]]) -> Tuple[List[str], int]:
# Build adjacency list and indegree map
adj: Dict[str, List[str]] = {t: [] for t in tasks}
indeg: Dict[str, int] = {t: 0 for t in tasks}
... | import heapq
from typing import List, Dict, Tuple
def schedule_dag(tasks: List[str], duration: Dict[str, int], precedence: List[List[str]]) -> Tuple[List[str], int]:
# Build adjacency list and in-degree count
# We need to find the lexicographically smallest topological order.
# This is done by always picki... | def check(candidate):
assert candidate(*(['A'], {'A': 10}, [])) == (['A'], 10)
assert candidate(*(['B', 'A'], {'A': 1, 'B': 2}, [['A', 'B']])) == (['A', 'B'], 3)
assert candidate(*(['c', 'a', 'b'], {'a': 3, 'b': 4, 'c': 5}, [])) == (['a', 'b', 'c'], 5)
assert candidate(*(['task1', 'task2', 'task3'], {'t... | 11 | 10 | 21 | 21 | 33 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02352 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | medium | Lexicographically Smallest Topological Order and Critical Path Length for a DAG | dag_schedule | You are given a directed acyclic graph (DAG) that represents a set of tasks and their precedence constraints.
**Function signature**
```python
from typing import List, Dict, Tuple
def dag_schedule(tasks: List[str], durations: Dict[str, int], dependencies: List[Tuple[str, str]]) -> Tuple[List[str], int]:
...
```
... | from typing import List, Dict, Tuple
import heapq
def dag_schedule(tasks: List[str], durations: Dict[str, int], dependencies: List[Tuple[str, str]]) -> Tuple[List[str], int]:
# Edge case: empty graph
if not tasks:
return ([], 0)
n = len(tasks)
# Build adjacency list and indegree map
adj: D... | from typing import List, Dict, Tuple
import heapq
def dag_schedule(tasks: List[str], durations: Dict[str, int], dependencies: List[Tuple[str, str]]) -> Tuple[List[str], int]:
if not tasks:
return ([], 0)
# Build adjacency list and in-degree count
adj = {t: [] for t in tasks}
in_degree = {t... | def check(candidate):
assert candidate(*([], {}, [])) == ([], 0)
assert candidate(*(['a'], {'a': 0}, [])) == (['a'], 0)
assert candidate(*(['b', 'a'], {'a': 1, 'b': 2}, [('a', 'b')])) == (['a', 'b'], 3)
assert candidate(*(['c', 'b', 'a'], {'a': 5, 'b': 3, 'c': 4}, [])) == (['a', 'b', 'c'], 5)
assert... | 10 | 11 | 21 | 18 | 48 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06353 | dynamic_programming | Knapsack variants (bounded, subset partitioning, minimum coin/item combination with tie-break) | false | hard | Minimum Value Knapsack with Tie‑Breakers | min_value_knapsack | You are given a list of items, each described by a dictionary with three keys:
- "weight": a positive integer representing the item's weight,
- "value": a non‑negative integer representing the item's value,
- "id": a unique string identifier (consisting of 1‑10 alphanumeric characters). The list is called `items` and ... | from typing import List, Dict, Any, Tuple
def min_value_knapsack(items: List[Dict[str, Any]], W: int) -> List[str]:
n = len(items)
# Edge case: no items
if n == 0:
return []
# Pre‑extract arrays for speed
weights = [it["weight"] for it in items]
values = [it["value"] for it in items]
... | from typing import List, Dict, Any
import copy
def min_value_knapsack(items: List[Dict[str, Any]], W: int) -> List[str]:
n = len(items)
# Edge case: W is 0, we need at least weight 0. The empty set has weight 0 >= 0, value 0, 0 items.
if W == 0:
return []
# If no items, can't reach an... | def check(candidate):
assert candidate(*([{'id': 'a', 'weight': 3, 'value': 4}, {'id': 'b', 'weight': 5, 'value': 2}, {'id': 'c', 'weight': 4, 'value': 2}], 7)) == ['b', 'c']
assert candidate(*([{'id': 'x', 'weight': 2, 'value': 5}, {'id': 'y', 'weight': 2, 'value': 5}], 5)) == []
assert candidate(*([{'id':... | 11 | 11 | 22 | 10 | 52 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04383 | dynamic_programming | 2D grid DP with obstacles, energy/budget constraints, and exact minimum cost | false | medium | Exact Minimum Cost Path with Obstacles and Budget | min_cost_path | You are given a rectangular 2‑D grid `grid` and an integer `budget`.
* `grid` is a list of `n` rows, each row is a list of `m` integers.
* `grid[i][j] >= 0` represents the energy cost to step on cell `(i, j)`.
* `grid[i][j] == -1` marks the cell as an obstacle; it cannot be entered.
* The start cell is the top‑left co... | from collections import deque
from typing import List
def min_cost_path(grid: List[List[int]], budget: int) -> int:
n = len(grid)
m = len(grid[0]) if n else 0
# dp[i][j] = minimal cost to reach (i,j) not exceeding budget, else None
# We can use BFS with a priority on cost (Dijkstra) but stop when cost ... | from typing import List
import heapq
def min_cost_path(grid: List[List[int]], budget: int) -> int:
if not grid or not grid[0]:
return -1
n = len(grid)
m = len(grid[0])
# Check if start or target is obstacle (shouldn't happen per constraints, but safety)
if grid[0][0] == -1 or grid... | def check(candidate):
assert candidate(*([[1, 2, 3], [2, -1, 4], [3, 2, 1]], 10)) == 9
assert candidate(*([[5, 5], [5, 5]], 12)) == -1
assert candidate(*([[0]], 0)) == 0
assert candidate(*([[7]], 5)) == -1
assert candidate(*([[1, 1, 1, 1, 1]], 5)) == 5
assert candidate(*([[1, -1, 1], [1, 1, 1], ... | 11 | 10 | 21 | 9 | 34 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06531 | state_machines_and_systems | Finite-state order/payment workflow engine processing event streams with guard rules | false | medium | Finite‑State Order Workflow Engine with Guard Rules | process_order_events | You are given a list of order events and a set of guard rules that constrain state transitions. Implement the function
```python
def process_order_events(events: List[Dict[str, Any]], guards: Dict[str, Dict[str, int]]) -> str:
```
* `events` is a list ordered by time (earliest first). Each event is a dictionary with ... | def process_order_events(events, guards):
# Define the state transition table
transition_table = {
('created', 'pay'): 'paid',
('created', 'cancel'): 'canceled',
('paid', 'ship'): 'shipped',
('paid', 'cancel'): 'canceled',
('shipped', 'deliver'): 'delivered',
('sh... | from typing import List, Dict, Any
def process_order_events(events: List[Dict[str, Any]], guards: Dict[str, Dict[str, int]]) -> str:
# Define the state transitions
# Key: (current_state, event_type) -> next_state
transitions = {
("created", "pay"): "paid",
("created", "cancel"): "canceled",... | def check(candidate):
assert candidate(*([{'type': 'pay', 'timestamp': 1, 'min_amount': 120}, {'type': 'ship', 'timestamp': 2, 'weight': 7}, {'type': 'deliver', 'timestamp': 3}], {'created->paid': {'min_amount': 100}, 'paid->ship': {'weight': 5}})) == 'delivered'
assert candidate(*([{'type': 'pay', 'timestamp':... | 11 | 9 | 20 | 4 | 39 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06547 | binary_search_and_greedy | Two-pointer / prefix-sum subarray bounds with negative numbers and modular constraints | false | medium-hard | Count Subarrays with Given Modulo Sum | count_mod_subarrays | You are to implement a function `count_mod_subarrays(arr: List[int], K: int, M: int) -> int`.
**Problem statement**
Given an integer array `arr` (its elements may be negative), a positive integer `K`, and a target remainder `M` such that `0 <= M < K`, return the number of contiguous subarrays (i.e., sub‑segments) whos... | def count_mod_subarrays(arr, K, M):
"""Return the number of contiguous subarrays whose sum modulo K equals M.
Args:
arr (List[int]): list of integers, may contain negatives.
K (int): positive modulus.
M (int): target remainder, 0 <= M < K.
Returns:
int: count of subarrays sa... | from typing import List
from collections import defaultdict
def count_mod_subarrays(arr: List[int], K: int, M: int) -> int:
"""
Count the number of contiguous subarrays whose sum modulo K equals M.
Uses prefix sums and a hash map to achieve O(N) time complexity.
For a subarray arr[i..j], sum = pre... | def check(candidate):
assert candidate(*([3, 1, 4, 1, 5], 5, 0)) == 4
assert candidate(*([-2, -3, 7, 1], 4, 3)) == 3
assert candidate(*([7], 5, 2)) == 1
assert candidate(*([8], 5, 2)) == 0
assert candidate(*([0, 0, 0, 0], 3, 0)) == 10
assert candidate(*([1, 2, 3, 4], 1000000000, 10)) == 1
as... | 10 | 11 | 21 | 7 | 26 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06002 | graph_and_network_algorithms | DAG scheduling, topological sort with lexicographic tie-breaking, critical path duration | false | hard | Lexicographic Topological Scheduling with Critical Path | critical_path_schedule | You are to implement the function `critical_path_schedule(tasks: List[Dict]) -> Dict`.
Each element of the input list `tasks` describes a single task in a project and is a dictionary with the following keys:
- "id": a unique string identifier consisting of 1 to 10 alphanumeric characters (A‑Z, a‑z, 0‑9). No two tasks ... | import heapq
from typing import List, Dict, Tuple
def critical_path_schedule(tasks: List[Dict]) -> Dict:
if not tasks:
return {"order": [], "critical_path": 0}
# Build mappings
id_to_idx = {task["id"]: i for i, task in enumerate(tasks)}
n = len(tasks)
indeg = [0] * n
adj: List[List[int]... | import heapq
from typing import List, Dict
def critical_path_schedule(tasks: List[Dict]) -> Dict:
if not tasks:
return {"order": [], "critical_path": 0}
# Build adjacency list and in-degree count
# We need to track: for each task, its duration, its dependencies, and its successors
task_map... | def check(candidate):
assert candidate(*([],)) == {'order': [], 'critical_path': 0}
assert candidate(*([{'id': 'X', 'duration': 7, 'deps': []}],)) == {'order': ['X'], 'critical_path': 7}
assert candidate(*([{'id': 'B', 'duration': 1, 'deps': []}, {'id': 'A', 'duration': 2, 'deps': []}],)) == {'order': ['A',... | 10 | 11 | 21 | 21 | 48 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06386 | strings_and_text_processing | Minimal line diff / longest common substring and alignment scoring | false | hard | Maximum Scoring Common Substring Alignment | max_scoring_common_substring | You are given two strings `a` and `b`, each consisting of only lowercase English letters (a‑z).
Define a *common substring* as a non‑empty string that appears contiguously in both `a` and `b`. For a common substring `s` that occurs in `a` starting at index `i` (0‑based) and in `b` starting at index `j` (0‑based), its ... | def max_scoring_common_substring(a: str, b: str) -> tuple:
n, m = len(a), len(b)
if n == 0 or m == 0:
return ("", -1, -1, 0)
# Ensure we iterate over the shorter string for memory efficiency
if m < n:
# swap roles but remember to swap back indices at the end
a, b = b, a
n... | def max_scoring_common_substring(a: str, b: str) -> tuple:
n = len(a)
m = len(b)
# If no common characters exist, return early
# We can check this by seeing if any character in a is in b
set_b = set(b)
has_common = False
for ch in a:
if ch in set_b:
has_common = True... | def check(candidate):
assert candidate(*('ababc', 'babca')) == ('babc', 1, 0, 15)
assert candidate(*('xyz', 'abc')) == ('', -1, -1, 0)
assert candidate(*('aaaa', 'aa')) == ('aa', 0, 0, 4)
assert candidate(*('abcde', 'cdeab')) == ('cde', 2, 0, 7)
assert candidate(*('abcd', 'abcd')) == ('abcd', 0, 0, ... | 15 | 10 | 25 | 17 | 54 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04233 | dynamic_programming | Knapsack variants (bounded, subset partitioning, minimum coin/item combination with tie-break) | false | medium | Minimum Item Count to Reach Exact Weight with Lexicographic Tie‑Break | min_items_knapsack | You are given a list of positive integers `weights` and a target integer `target`. Each weight represents an item that can be used **at most once** (i.e., a bounded/0‑1 knapsack). Your task is to select a subset of items whose total weight is exactly `target` and that uses the **fewest number of items**.
If multiple s... | from typing import List
def min_items_knapsack(weights: List[int], target: int) -> List[int]:
n = len(weights)
# dp[t] = (min_count, index_list) achieving weight t, or None if unreachable
INF = 10**9
dp = [(INF, []) for _ in range(target + 1)]
dp[0] = (0, [])
for idx, w in enumerate(weights):
... | from typing import List
def min_items_knapsack(weights: List[int], target: int) -> List[int]:
n = len(weights)
if target == 0:
return []
if n == 0:
return []
# dp[i] = (min_items, best_indices_tuple) to reach sum i
# We use a list where dp[s] stores the best (count, indices_tup... | def check(candidate):
assert candidate(*([4, 2, 5, 3, 7], 9)) == [0, 2]
assert candidate(*([1, 2, 3], 7)) == []
assert candidate(*([5, 10, 15], 0)) == []
assert candidate(*([1, 2, 3, 4], 10)) == [0, 1, 2, 3]
assert candidate(*([6, 1, 5, 2, 3], 7)) == [0, 1]
assert candidate(*([1, 2, 3, 4, 5, 6, ... | 13 | 9 | 22 | 9 | 27 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04492 | graph_and_network_algorithms | Minimum spanning tree / network clustering with mandatory or forbidden edges | false | medium-hard | Minimum Cost Forest with Mandatory and Forbidden Edges | min_spanning_cluster_cost | Write a function `min_spanning_cluster_cost(edges, mandatory, forbidden, k)` that computes the minimum possible total weight of a set of edges satisfying all of the following conditions:
* The input graph is undirected, has `n` vertices numbered from `0` to `n-1` where `n` is the largest vertex index appearing in any ... | import heapq
from typing import List
class DSU:
def __init__(self, n: int):
self.parent = list(range(n))
self.rank = [0] * n
self.components = n
def find(self, x: int) -> int:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = se... | from typing import List
def min_spanning_cluster_cost(edges: List[List[int]], mandatory: List[int], forbidden: List[int], k: int) -> int:
if not edges:
# No edges, n=0? But constraints say len(edges) >= 1, so this shouldn't happen.
# If n=0, k must be 0? But k>=1. So impossible.
return -1
... | def check(candidate):
assert candidate(*([[0, 1, 4], [1, 2, 3], [0, 2, 5], [2, 3, 2]], [1], [2], 2)) == 5
assert candidate(*([[0, 1, 1], [1, 2, 1], [2, 3, 1], [3, 0, 1]], [], [], 1)) == 3
assert candidate(*([], [], [], 0)) == -1
assert candidate(*([[0, 1, 2], [1, 2, 2], [0, 2, 2]], [0, 1], [], 1)) == 4
... | 12 | 10 | 22 | 11 | 62 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07657 | binary_search_and_greedy | Two-pointer / prefix-sum subarray bounds with negative numbers and modular constraints | false | medium-hard | Count subarrays with sum divisible by M | count_subarrays_divisible | Write a function `count_subarrays_divisible(arr: List[int], m: int) -> int` that returns the number of contiguous sub‑arrays of `arr` whose element sum is divisible by `m`.
**Definitions**
- A *sub‑array* is a slice `arr[l..r]` (0‑based inclusive) for some `0 ≤ l ≤ r < len(arr)`.
- The *sum* of a sub‑array is the arit... | def count_subarrays_divisible(arr, m):
"""Return the number of contiguous sub‑arrays whose sum is divisible by m.
Parameters
----------
arr : List[int]
List of integers, may contain negative numbers.
m : int
Positive divisor.
"""
if not arr:
return 0
# prefix mod... | from typing import List
from collections import defaultdict
def count_subarrays_divisible(arr: List[int], m: int) -> int:
if not arr:
return 0
# Use prefix sums and modulo arithmetic
# If prefix_sum[i] % m == prefix_sum[j] % m (with i < j),
# then subarray arr[i+1..j] has sum divisible by ... | def check(candidate):
assert candidate(*([1, 2, 3, 4, 5], 3)) == 7
assert candidate(*([5, -2, 3, 0, 1], 5)) == 2
assert candidate(*([], 7)) == 0
assert candidate(*([6, 12, 18], 6)) == 6
assert candidate(*([1, 1, 1, 1], 5)) == 0
assert candidate(*([2, -1, 4], 100)) == 0
assert candidate(*([10... | 11 | 10 | 21 | 8 | 22 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03347 | binary_search_and_greedy | Parametric binary search on answer (minimize max load, shipping capacity, bandwidth allocation) | false | hard | Minimum Possible Maximum Load on Machines | minimum_max_load | You are given a list of positive integers `jobs` and an integer `m`. Each integer in `jobs` represents the processing time of a job. You have exactly `m` identical machines. All jobs must be assigned to a machine; a machine can process any number of jobs sequentially, and the total load of a machine is the sum of proce... | from typing import List
def minimum_max_load(jobs: List[int], m: int) -> int:
# Helper to decide if a given capacity 'limit' can accommodate all jobs on at most m machines.
def feasible(limit: int) -> bool:
used = 1 # start with one machine
current = 0
for job in jobs:
if c... | from typing import List
def minimum_max_load(jobs: List[int], m: int) -> int:
"""
Compute the smallest possible value L such that it is possible to assign
every job to one of m machines and no machine receives a total load greater than L.
Uses binary search on the answer L with a greedy feasibilit... | def check(candidate):
assert candidate(*([5], 1)) == 5
assert candidate(*([3, 1, 4, 1, 5], 5)) == 5
assert candidate(*([2, 2, 2, 2], 1)) == 8
assert candidate(*([7, 2, 5, 10, 8], 2)) == 18
assert candidate(*([1, 2, 3, 4, 5], 3)) == 6
assert candidate(*([4, 4, 4, 4], 2)) == 8
assert candidate... | 10 | 10 | 20 | 16 | 26 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03595 | binary_search_and_greedy | Parametric binary search on answer (minimize max load, shipping capacity, bandwidth allocation) | false | medium-hard | Minimum Possible Maximum Load for Workers | minimum_max_load | You are given a list of non‑negative integer task durations `tasks` and a positive integer `workers`.
Each worker must be assigned a contiguous subsequence of tasks (the order of tasks cannot be changed). Every task must be assigned to exactly one worker, and each worker must receive at least one task.
Define the *lo... | import bisect
from typing import List
def minimum_max_load(tasks: List[int], workers: int) -> int:
n = len(tasks)
if workers > n:
return -1
# Helper: can we split into at most `workers` parts with each part sum <= limit?
def feasible(limit: int) -> bool:
cnt = 1
cur = 0
... | from typing import List
def minimum_max_load(tasks: List[int], workers: int) -> int:
n = len(tasks)
# If workers > n, impossible since each worker needs at least one task
if workers > n:
return -1
# If workers == 0, but constraint says workers >= 1, so not needed
# If workers == 1... | def check(candidate):
assert candidate(*([10, 20, 30, 40], 2)) == 60
assert candidate(*([5, 5, 5, 5, 5], 3)) == 10
assert candidate(*([1, 2, 3, 4, 5], 5)) == 5
assert candidate(*([7, 3, 9, 2], 1)) == 21
assert candidate(*([4, 8], 3)) == -1
assert candidate(*([0, 0, 0, 0], 2)) == 0
assert can... | 10 | 9 | 19 | 13 | 31 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.