Datasets:
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-08080 | 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 | compute_critical_path | You are given a directed acyclic graph (DAG) that models a set of tasks and precedence constraints.\n\nEach task is identified by an integer ID from 1 to `num_tasks` (inclusive) and has a positive integer duration. The graph is described by two collections:\n\n* `durations`: a list of length `num_tasks` where `duration... | import heapq
from typing import List, Tuple
def compute_critical_path(num_tasks: int, durations: List[int], dependencies: List[Tuple[int, int, int]]) -> Tuple[List[int], int]:
# Build adjacency list and indegree count, ignoring duplicate edges.
adj = [[] for _ in range(num_tasks + 1)] # 1βbased indexing
i... | from typing import List, Tuple
import heapq
def compute_critical_path(num_tasks: int, durations: List[int], dependencies: List[Tuple[int, int, int]]) -> Tuple[List[int], int]:
# Build adjacency list and in-degree count
# Tasks are 1-indexed, so we'll use size num_tasks + 1 for convenience
adj = [[] for _ i... | def check(candidate):
assert candidate(*(1, [7], [])) == ([1], 7)
assert candidate(*(2, [3, 4], [(1, 2, 0)])) == ([1, 2], 7)
assert candidate(*(4, [2, 2, 2, 2], [(1, 3, 0), (2, 3, 0)])) == ([1, 2, 3, 4], 4)
assert candidate(*(3, [5, 1, 2], [(1, 2, 0), (1, 2, 0), (2, 3, 0)])) == ([1, 2, 3], 8)
assert... | 12 | 11 | 23 | 19 | 50 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04621 | state_machines_and_systems | Vector-clock / Lamport timestamp causality comparator and concurrent event detector | false | medium-hard | Vector Clock Causality Comparator | compare_vector_clocks | You are given two vector clocks `vc1` and `vc2`. A vector clock is represented as a list of nonβnegative integers of equal length `n` ( 1 β€ n β€ 1000 ). Each position `i` corresponds to process `i` and stores the number of events that process has observed.
Define the relation:
* `vc1` *happenedβbefore* `vc2` (written `... | from typing import List
def compare_vector_clocks(vc1: List[int], vc2: List[int]) -> int:
if len(vc1) != len(vc2):
raise ValueError("Vector clocks must have the same length")
# Validate nonβnegative values
for a, b in zip(vc1, vc2):
if a < 0 or b < 0:
raise ValueError("Vector cl... | def compare_vector_clocks(vc1: list, vc2: list) -> int:
if len(vc1) != len(vc2):
raise ValueError("Vector clocks must have the same length")
for v in vc1 + vc2:
if v < 0:
raise ValueError("Vector clock elements must be non-negative")
n = len(vc1)
all_leq = True
... | def check(candidate):
assert candidate(*([1, 2, 3], [2, 2, 4])) == -1
assert candidate(*([5, 0, 2], [3, 0, 2])) == 1
assert candidate(*([5, 0, 2], [3, 1, 2])) == 0
assert candidate(*([0, 0, 0], [0, 0, 0])) == 0
assert candidate(*([7], [9])) == -1
assert candidate(*([10], [2])) == 1
assert ca... | 10 | 9 | 19 | 3 | 24 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02718 | data_engineering_and_pipelines | In-memory relational join / group-by / window-rank engine over list-of-dict records | false | medium | In-memory relational join with group-by and topβk window ranking | join_groupby_topk | You are given two tables represented as lists of dictionaries. Each dictionary describes a row, mapping column names (strings) to integer values. Implement a function
```python
join_groupby_topk(left: List[Dict[str, int]], right: List[Dict[str, int]],
left_key: str, right_key: str,
grou... | from typing import List, Dict, Tuple
def join_groupby_topk(left: List[Dict[str, int]], right: List[Dict[str, int]],
left_key: str, right_key: str,
group_by: List[str], order_by: str, k: int) -> List[Dict[str, int]]:
# Step 0: trivial k==0
if k == 0:
return ... | from typing import List, Dict
def join_groupby_topk(left: List[Dict[str, int]], right: List[Dict[str, int]],
left_key: str, right_key: str,
group_by: List[str], order_by: str, k: int) -> List[Dict[str, int]]:
if k == 0:
return []
# Step 1: Inner Join
# B... | def check(candidate):
assert candidate(*([{'id': 1, 'dept': 10, 'val': 5}, {'id': 2, 'dept': 10, 'val': 7}], [{'ref': 1, 'score': 50}, {'ref': 2, 'score': 60}], 'id', 'ref', ['dept'], 'score', 5)) == [{'ref': 2, 'score': 60, 'id': 2, 'dept': 10, 'val': 7}, {'ref': 1, 'score': 50, 'id': 1, 'dept': 10, 'val': 5}]
... | 10 | 12 | 22 | 13 | 44 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03559 | 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 | compute_total_liability | You are to implement a function `compute_total_liability(income: int, transactions: List[int]) -> int`.
**Definitions**
- `income` is the yearly gross income of a person, expressed in **cents** (i.e., 1 dollar = 100). It is a nonβnegative integer.
- `transactions` is a list of monetary transaction amounts, each expres... | def compute_total_liability(income: int, transactions: list) -> int:
"""Calculate total tax and transaction fees in cents.
Args:
income: yearly gross income in cents (nonβnegative integer).
transactions: list of transaction amounts in cents (each nonβnegative integer).
Returns:
Tot... | from decimal import Decimal, ROUND_HALF_UP
def compute_total_liability(income: int, transactions: list) -> int:
# Calculate progressive tax
tax = 0
remaining_income = income
# Bracket 1: first 1,000,000 cents at 10%
bracket1_limit = 1_000_000
if remaining_income > 0:
taxable_in_bra... | def check(candidate):
assert candidate(*(2500000, [1200, 3400])) == 325114
assert candidate(*(0, [])) == 0
assert candidate(*(1000000, [10000])) == 100080
assert candidate(*(5000000, [1, 2, 3, 4, 5])) == 800250
assert candidate(*(1000000000, [])) == 199800000
assert candidate(*(0, [1667, 3333, 5... | 14 | 9 | 23 | 22 | 40 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03798 | math_and_combinatorics | 2D integer computational geometry (convex hull, doubled polygon area, segment intersection) | false | medium | Count interior segment intersections | count_intersections | Write a function `count_intersections(segments: List[Tuple[Tuple[int, int], Tuple[int, int]]]) -> int` that receives a list of closed line segments in the 2βdimensional integer plane and returns the number of unordered pairs of segments that intersect at a point that lies strictly inside **both** segments. An intersec... | from typing import List, Tuple
def _orientation(ax: int, ay: int, bx: int, by: int, cx: int, cy: int) -> int:
"""Return the orientation of the triplet (a,b,c).
>0 if counterβclockwise, <0 if clockwise, 0 if collinear.
"""
return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)
def _on_segment(ax: int, ay... | from typing import List, Tuple
import math
def count_intersections(segments: List[Tuple[Tuple[int, int], Tuple[int, int]]]) -> int:
"""
Count the number of unordered pairs of segments that intersect at a point
strictly inside both segments.
"""
# Filter out degenerate segments (where both endpoints... | def check(candidate):
assert candidate(*([((0, 0), (4, 4)), ((0, 4), (4, 0))],)) == 1
assert candidate(*([((0, 0), (2, 0)), ((2, 0), (4, 0))],)) == 0
assert candidate(*([((0, 0), (2, 0)), ((0, 1), (2, 1))],)) == 0
assert candidate(*([((0, 0), (4, 0)), ((2, 0), (6, 0))],)) == 1
assert candidate(*([((... | 13 | 5 | 18 | 5 | 62 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03450 | math_and_combinatorics | 2D integer computational geometry (convex hull, doubled polygon area, segment intersection) | false | medium | Double the Area of the Convex Hull | double_convex_hull_area | You are given a list `points` containing *N* distinct integer lattice points in the plane. Each point is represented as a twoβelement list `[x, y]` where `x` and `y` are 32βbit signed integers. Your task is to compute **twice** the area of the convex hull of these points and return it as a nonβnegative integer.
**Func... | def double_convex_hull_area(points):
# Helper: cross product of OA x OB
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
n = len(points)
if n < 3:
return 0
# Sort points lexicographically (first x, then y)
pts = sorted(points)
# Build ... | def double_convex_hull_area(points: list) -> int:
if not points or len(points) < 3:
return 0
# Convert to tuples for immutability and hashing if needed
pts = [tuple(p) for p in points]
# Sort points lexicographically
pts.sort()
# Build lower hull
lower = []
for p i... | def check(candidate):
assert candidate(*([],)) == 0
assert candidate(*([[0, 0]],)) == 0
assert candidate(*([[1, 2], [3, 4]],)) == 0
assert candidate(*([[0, 0], [2, 0], [1, 1]],)) == 2
assert candidate(*([[0, 0], [1, 0], [2, 0], [0, 2], [2, 2]],)) == 8
assert candidate(*([[0, 0], [5, 0], [0, 5]],... | 12 | 8 | 20 | 10 | 34 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07734 | strings_and_text_processing | Fuzzy string search, k-mismatch pattern finder, and palindrome partitioning | false | medium | Fuzzy Pattern Finder with Minimum Palindrome Partitions | fuzzy_pattern_palindrome | You are to implement a function with the exact signature:
```python
def fuzzy_pattern_palindrome(text: str, pattern: str, k: int) -> dict:
```
The function searches `text` for occurrences of `pattern` that differ in at most `k` positions (a *kβmismatch* match). An occurrence is defined by its starting index (0βbased)... | def fuzzy_pattern_palindrome(text: str, pattern: str, k: int) -> dict:
# Edge case: empty pattern -> no matches, whole text remains
if len(pattern) == 0:
return {"positions": [], "pal_partitions": _min_pal_partitions(text)}
n, m = len(text), len(pattern)
positions = []
i = 0
while i <= ... | def fuzzy_pattern_palindrome(text: str, pattern: str, k: int) -> dict:
# Edge case: empty pattern matches everywhere but we select none
if len(pattern) == 0:
# Remaining string is original text
pal_partitions = _min_palindrome_partitions(text)
return {"positions": [], "pal_partitions": p... | def check(candidate):
assert candidate(*('abacabad', 'aba', 1)) == {'positions': [0, 4], 'pal_partitions': 2}
assert candidate(*('aaaaa', 'aa', 0)) == {'positions': [0, 2], 'pal_partitions': 1}
assert candidate(*('', 'a', 0)) == {'positions': [], 'pal_partitions': 0}
assert candidate(*('abc', '', 0)) ==... | 14 | 9 | 23 | 14 | 57 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06401 | 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 `vc_a` and `vc_b`. A vector clock is represented as a JSON object (Python ``dict``) that maps a process identifier (a nonβempty string consisting of ASCII letters, digits or underscore) to a nonβnegative integer logical timestamp. The clocks may contain different sets of processes; any p... | def compare_vector_clocks(vc_a: dict, vc_b: dict) -> int:
"""Return -1 if vc_a happens before vc_b, 1 if after, 0 if concurrent.
Missing keys are treated as timestamp 0.
"""
# Gather all process identifiers
keys = set(vc_a.keys()) | set(vc_b.keys())
a_before_b = False
b_before_a = False
... | def compare_vector_clocks(vc_a: dict, vc_b: dict) -> int:
# Collect all unique process identifiers from both clocks
all_processes = set(vc_a.keys()) | set(vc_b.keys())
# Track whether a < b (found at least one p where a[p] < b[p])
# and whether a > b (found at least one p where a[p] > b[p])
a_l... | def check(candidate):
assert candidate(*({'p1': 2, 'p2': 1}, {'p1': 3, 'p2': 1})) == -1
assert candidate(*({'p1': 5, 'p2': 0}, {'p1': 2, 'p2': 0})) == 1
assert candidate(*({'p1': 1}, {'p2': 1})) == 0
assert candidate(*({'a': 0, 'b': 2}, {'a': 0, 'b': 2})) == 0
assert candidate(*({'x': 0}, {'x': 0, '... | 12 | 11 | 23 | 3 | 24 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04242 | graph_and_network_algorithms | Minimum spanning tree / network clustering with mandatory or forbidden edges | false | medium | Constrained Minimum Spanning Forest with Mandatory and Forbidden Edges | compute_mst_clusters | You are given an undirected weighted graph with vertices numbered from 1 to n.
**Function signature**
```python
def compute_mst_clusters(
n: int,
edges: List[Tuple[int, int, int]],
mandatory: List[Tuple[int, int]],
forbidden: List[Tuple[int, int]],
k: int,
) -> List[Tuple[int, int, int]]:
```
* `n`... | def compute_mst_clusters(
n: int,
edges: list,
mandatory: list,
forbidden: list,
k: int,
) -> list:
# Helper: Disjoint Set Union (UnionβFind)
class DSU:
__slots__ = ("parent", "rank")
def __init__(self, size: int):
self.parent = list(range(size + 1))
s... | from typing import List, Tuple
def compute_mst_clusters(
n: int,
edges: List[Tuple[int, int, int]],
mandatory: List[Tuple[int, int]],
forbidden: List[Tuple[int, int]],
k: int,
) -> List[Tuple[int, int, int]]:
# Union-Find data structure
parent = list(range(n + 1))
rank = [0] * (n + 1)
... | def check(candidate):
assert candidate(*(4, [(1, 2, 1), (1, 3, 2), (2, 3, 2), (2, 4, 3), (3, 4, 4)], [(1, 2)], [(2, 4)], 2)) == [(1, 2, 1), (1, 3, 2)]
assert candidate(*(3, [(1, 2, 5), (1, 3, 5), (2, 3, 5)], [(1, 2), (2, 3)], [], 1)) == [(1, 2, 5), (2, 3, 5)]
assert candidate(*(5, [(1, 2, 4), (1, 3, 3), (2,... | 12 | 11 | 23 | 15 | 80 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05461 | state_machines_and_systems | Finite-state order/payment workflow engine processing event streams with guard rules | false | medium-hard | Finite-state order workflow engine with guard rules | process_events | You are given a list of events that represent actions on eβcommerce orders. Each event is a twoβelement tuple ``(order_id, event_type)`` where:
- ``order_id`` is a nonβempty string consisting of alphanumeric characters and hyphens.
- ``event_type`` is one of the following exact strings:
- ``"create"`` β a new o... | def process_events(events):
"""Process a list of order events and return final states and ignored count.
Args:
events (List[Tuple[str, str]]): List of (order_id, event_type).
Returns:
Tuple[Dict[str, str], int]: (final_states, ignored_count).
"""
# Define valid transitions: current_... | def process_events(events):
# State transitions:
# create -> NEW
# pay -> PAID (from NEW)
# ship -> SHIPPED (from PAID)
# cancel -> CANCELLED (from NEW or PAID)
# refund -> REFUNDED (from SHIPPED)
# Map event_type to allowed previous states
allowed_transitions = {
"create": ... | def check(candidate):
assert candidate(*([('order1', 'create'), ('order1', 'pay'), ('order1', 'ship')],)) == ({'order1': 'SHIPPED'}, 0)
assert candidate(*([('o', 'create'), ('o', 'create'), ('o', 'pay')],)) == ({'o': 'PAID'}, 1)
assert candidate(*([('c1', 'create'), ('c1', 'cancel'), ('c1', 'pay')],)) == ({... | 11 | 11 | 22 | 20 | 37 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-04395 | parsing_and_compilers | Nested bracket/macro template expander with syntax and cycle error handling | false | medium | Recursive Macro Template Expander with Cycle and Undefined Detection | expand_template | You are given a template string `template` and a dictionary `definitions` mapping macro names to their replacement strings. Macros are denoted by double curly braces, e.g. `{{NAME}}`. A macro name consists of one or more uppercase English letters (`A-Z`). The replacement string may itself contain macros, which must be ... | import re
from typing import Dict, Set
def expand_template(template: str, definitions: Dict[str, str]) -> str:
macro_pattern = re.compile(r"{{([A-Z]{1,20})}}")
def replace_once(s: str, stack: Set[str]) -> (str, bool, bool):
"""Perform one leftβtoβright pass.
Returns (new_string, found_macro, e... | import re
from typing import Dict
def expand_template(template: str, definitions: Dict[str, str]) -> str:
# We need to expand macros left-to-right, single-pass per iteration.
# A macro is {{NAME}} where NAME is one or more uppercase letters.
# We must detect undefined macros and cyclic dependencies.
... | def check(candidate):
assert candidate(*('Hello, {{NAME}}!', {'NAME': 'Alice'})) == 'Hello, Alice!'
assert candidate(*('{{GREETING}}, world!', {'HELLO': 'Hi'})) == 'UNDEFINED'
assert candidate(*('{{A}}', {'A': '{{A}}'})) == 'CYCLIC'
assert candidate(*('{{X}}', {'X': '{{Y}}', 'Y': '{{Z}}', 'Z': '{{X}}'})... | 13 | 12 | 25 | 18 | 44 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-07513 | dynamic_programming | Knapsack variants (bounded, subset partitioning, minimum coin/item combination with tie-break) | false | medium-hard | Minimum weight to reach target value with tieβbreak on item count | min_weight_for_value | Write a function `min_weight_for_value(items: List[List[int]], target: int) -> Tuple[int, int]` that solves the following problem.
You are given a list `items` of length *n* (0β―β€β―nβ―β€β―30). Each element `items[i]` is a twoβelement list `[w_i, v_i]` where `w_i` (1β―β€β―w_iβ―β€β―10β΄) is the weight of the iβth item and `v_i` (1β―... | def min_weight_for_value(items, target):
# Edge case: target 0 -> empty subset
if target == 0:
return (0, 0)
n = len(items)
if n == 0:
return (-1, -1)
total_value = sum(v for _, v in items)
max_val = max(target, total_value)
INF_WEIGHT = 10**15
INF_COUNT = 10**9
# dp[... | def min_weight_for_value(items: list, target: int) -> tuple:
if target <= 0:
return (0, 0)
n = len(items)
if n == 0:
return (-1, -1)
# Calculate total value to determine DP table size
total_value = sum(v for _, v in items)
# If total value is less than target, impo... | def check(candidate):
assert candidate(*([[2, 3], [5, 8], [3, 4]], 10)) == (7, 2)
assert candidate(*([[4, 5], [6, 7], [3, 3]], 9)) == (9, 2)
assert candidate(*([], 0)) == (0, 0)
assert candidate(*([], 5)) == (-1, -1)
assert candidate(*([[10, 15]], 15)) == (10, 1)
assert candidate(*([[7, 20]], 10... | 12 | 11 | 23 | 17 | 36 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06861 | state_machines_and_systems | Memory allocator simulator (first-fit / best-fit free list with adjacent block coalescing) | false | medium | Memory Allocator Simulator with FirstβFit / BestβFit and Coalescing | simulate_allocator | You are to implement a memory allocator simulator.
**Function signature**
```python
def simulate_allocator(total_size: int, ops: List[Tuple[str, int]], strategy: str) -> Dict[str, Any]:
```
- `total_size` (int): total size of the linear memory, measured in bytes. It is guaranteed to be a positive integer (1β―β€β―total_si... | import bisect
from typing import List, Tuple, Dict, Any
def simulate_allocator(total_size: int, ops: List[Tuple[str, int]], strategy: str) -> Dict[str, Any]:
# free list stored as list of [start, size], always sorted by start
free = [[0, total_size]]
# allocated blocks: id -> (start, size)
allocated: D... | def simulate_allocator(total_size: int, ops: list, strategy: str) -> dict:
# Internal state
# free_blocks: list of [start, size] sorted by start address
free_blocks = [[0, total_size]]
# allocated_blocks: dict mapping block_id -> [start, size]
allocated_blocks = {}
next_id = 1
results = []
... | def check(candidate):
assert candidate(*(100, [('alloc', 10), ('alloc', 20), ('free', 1), ('alloc', 15)], 'first')) == {'results': [1, 2, True, 3], 'free_blocks': [[0, 10], [45, 55]]}
assert candidate(*(50, [('alloc', 30), ('alloc', 25), ('free', 1), ('alloc', 20)], 'best')) == {'results': [1, -1, True, 2], 'fr... | 10 | 12 | 22 | 20 | 73 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05346 | strings_and_text_processing | Minimal line diff / longest common substring and alignment scoring | false | medium | Minimal Line Difference via Longest Common Substring | minimal_line_diff_score | You are to implement the function `minimal_line_diff_score(a: str, b: str) -> int`.
**Problem definition**
Given two strings `a` and `b`, let `L` be the length of their *longest common substring* (a substring is a contiguous sequence of characters; the substring may appear at any position in each string). The *minimal... | def minimal_line_diff_score(a: str, b: str) -> int:
"""Return len(a) + len(b) - 2 * L where L is the length of the longest common substring.
Uses a rollingβhash binaryβsearch approach to achieve O(n+m) time.
"""
n, m = len(a), len(b)
if n == 0 or m == 0:
return n + m
# Ensure a is the sh... | def minimal_line_diff_score(a: str, b: str) -> int:
n = len(a)
m = len(b)
# If either string is empty, L = 0
if n == 0 or m == 0:
return n + m
# We need to find the length of the longest common substring.
# To achieve O(n + m) time and O(min(n, m)) space, we use a suffix automa... | def check(candidate):
assert candidate(*('ababc', 'babca')) == 2
assert candidate(*('hello', 'world')) == 8
assert candidate(*('', '')) == 0
assert candidate(*('', 'nonempty')) == 8
assert candidate(*('aaaaa', 'aaa')) == 2
assert candidate(*('abcde', 'cdeab')) == 4
assert candidate(*('xyz', ... | 10 | 11 | 21 | 7 | 39 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-02500 | math_and_combinatorics | Modular arithmetic, prime factorization, Euler totient, and matrix exponentiation mod M | false | medium-hard | FibonacciβTotient Product Modulo | fib_totient_product | Write a function `fib_totient_product(N: int, M: int) -> int` that returns the product of the Nβth Fibonacci number (with F(0)=0, F(1)=1) and Euler's totient of N, taken modulo M.
**Definitions**
- The Fibonacci sequence is defined by F(0)=0, F(1)=1 and F(k)=F(kβ1)+F(kβ2) for kβ₯2.
- Euler's totient Ο(N) is the count o... | import math
def _matrix_mul(a, b, 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 _matrix_pow(mat, power, mod):
# fast exponentiation of 2x2 m... | def fib_totient_product(N: int, M: int) -> int:
if M == 1:
return 0
# Compute F(N) mod M using fast matrix exponentiation
def fib_mod(n, mod):
if n == 0:
return 0
if n == 1:
return 1 % mod
# Matrix exponentiation: [[1,1],[1,0]]^n
... | def check(candidate):
assert candidate(*(1, 5)) == 1
assert candidate(*(2, 10)) == 1
assert candidate(*(10, 1000)) == 220
assert candidate(*(100, 1000003)) == 654355
assert candidate(*(123456789, 1000000007)) == 880563157
assert candidate(*(999999937, 1000000007)) == 849972590
assert candida... | 14 | 10 | 24 | 13 | 46 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-06996 | strings_and_text_processing | Custom tokenization, run-length / LZ-style lossless compression and decompression | false | medium | Custom Run-Length Tokenizer with Substring Repetition | custom_compress | You are to implement a lossβless compression algorithm for strings.
**Function signature**
```python
def custom_compress(text: str) -> str:
```
**Compression rules**
1. Scan the input from left to right.
2. At each position try to find a *repetition block*:
* Choose a substring `sub` (length `L >= 1`) such that `s... | def custom_compress(text: str) -> str:
n = len(text)
i = 0
out_parts = []
while i < n:
best_len = 0
best_k = 0
# maximum possible length is remaining chars // 2 because at least two repeats needed
max_len = (n - i) // 2
for L in range(max_len, 0, -1):
... | def custom_compress(text: str) -> str:
n = len(text)
if n == 0:
return ""
result = []
i = 0
while i < n:
# Try to find the longest repetition block starting at i
best_k = 0
best_sub = ""
# We need to find the longest sub such that text[i:i+L*k] =... | def check(candidate):
assert candidate(*('',)) == ''
assert candidate(*('a',)) == 'a'
assert candidate(*('aa',)) == '2(a)'
assert candidate(*('ababa',)) == '2(ab)a'
assert candidate(*('aaaaaa',)) == '2(aaa)'
assert candidate(*('abcabcabc',)) == '3(abc)'
assert candidate(*('abcabcab',)) == '2... | 14 | 9 | 23 | 23 | 25 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-05851 | state_machines_and_systems | Vector-clock / Lamport timestamp causality comparator and concurrent event detector | false | medium-hard | Vector Clock Causality Comparator | compare_vector_clocks | You are given two vector clocks `vc1` and `vc2`. Each vector clock is represented as a JSON object (Python dict) that maps process identifiers (strings) to nonβnegative integers (the logical clock value for that process). All process identifiers that appear in either clock are considered part of the system.
Define a f... | def compare_vector_clocks(vc1, vc2):
"""Compare two vector clocks.
Args:
vc1 (dict): mapping process id (str) -> nonβnegative int.
vc2 (dict): same as vc1.
Returns:
str: "happens_before", "happens_after" or "concurrent".
"""
# Gather all keys
keys = set(vc1) | set(vc2)
... | def compare_vector_clocks(vc1: dict, vc2: dict) -> str:
# Get the union of all process identifiers
all_keys = set(vc1.keys()) | set(vc2.keys())
vc1_leq_vc2 = True # vc1 <= vc2 for all keys
vc2_leq_vc1 = True # vc2 <= vc1 for all keys
vc1_lt_vc2 = False # vc1 < vc2 for at least one key
vc... | def check(candidate):
assert candidate(*({'A': 1, 'B': 0}, {'A': 2, 'B': 0})) == 'happens_before'
assert candidate(*({'X': 5, 'Y': 3}, {'X': 4, 'Y': 3})) == 'happens_after'
assert candidate(*({'P': 2, 'Q': 5}, {'P': 3, 'Q': 4})) == 'concurrent'
assert candidate(*({'M': 7, 'N': 2}, {'M': 7, 'N': 2})) == ... | 14 | 11 | 25 | 3 | 30 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-08187 | binary_search_and_greedy | Two-pointer / prefix-sum subarray bounds with negative numbers and modular constraints | false | medium | Shortest subarray with given modular sum | min_subarray_len_mod | You are given a list of integers `arr`, an integer modulus `m` (m > 0) and a target remainder `k` (0 β€ k < m). A *subarray* is a contiguous slice of `arr`. Define the *modular sum* of a subarray as the sum of its elements taken modulo `m` (i.e. (sum of elements) % m). Implement a function
```python
def min_subarray... | def min_subarray_len_mod(arr, m, k):
# prefix_mod -> earliest index where this mod appears
earliest = {0: -1} # prefix sum of 0 before the array starts
prefix = 0
best = float('inf')
for i, val in enumerate(arr):
prefix = (prefix + val) % m
# we need a previous prefix_mod such that ... | def min_subarray_len_mod(arr: list[int], m: int, k: int) -> int:
n = len(arr)
# We need to find the shortest subarray [i..j] such that (prefix[j+1] - prefix[i]) % m == k
# This is equivalent to: prefix[j+1] % m - prefix[i] % m == k (mod m)
# Or: prefix[i] % m == (prefix[j+1] % m - k) % m
# Let'... | def check(candidate):
assert candidate(*([3, 1, 4, 2, 5], 6, 0)) == 2
assert candidate(*([-1, 2, -3, 4, -5], 7, 3)) == 3
assert candidate(*([5], 10, 5)) == 1
assert candidate(*([5], 10, 3)) == -1
assert candidate(*([0, 0, 0], 1, 0)) == 1
assert candidate(*([1, 2, 3], 100, 50)) == -1
assert c... | 11 | 10 | 21 | 4 | 17 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-03764 | data_structures_and_heaps | LRU/LFU cache simulator or TTL-expiring key-value store state transition function | false | hard | TTLβexpiring keyβvalue store simulator | simulate_ttl_store | You are to implement a deterministic simulator for a keyβvalue store where each entry automatically expires after a fixed number of operations (its TTL β timeβtoβlive). The store supports two operation types:
* **set** β stores a value under a key, recording the current operation index as the entry's timestamp.
* **ge... | import collections
from typing import List, Dict, Any, Optional
def simulate_ttl_store(ops: List[Dict[str, Any]], ttl: int) -> List[Optional[int]]:
# store: key -> (value, timestamp)
store: Dict[str, tuple[int, int]] = {}
result: List[Optional[int]] = []
for idx, op in enumerate(ops):
# 1. Expi... | def simulate_ttl_store(ops: list, ttl: int) -> list:
store = {} # key -> (value, timestamp)
results = []
for i, op in enumerate(ops):
# Step 1: Expiration step
# Remove all keys whose stored timestamp t satisfies current_index > t + ttl
# i.e., t < i - ttl
keys_to_remov... | def check(candidate):
assert candidate(*([{'type': 'set', 'key': 'a', 'value': 10}, {'type': 'get', 'key': 'a'}, {'type': 'get', 'key': 'a'}], 1)) == [10, None]
assert candidate(*([{'type': 'set', 'key': 'k', 'value': 5}, {'type': 'get', 'key': 'k'}, {'type': 'set', 'key': 'k', 'value': 6}, {'type': 'get', 'key... | 10 | 11 | 21 | 15 | 26 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
pc-08365 | binary_search_and_greedy | Multi-server priority queue / load-balancer deterministic event simulation | false | medium-hard | Deterministic Multi-Server Load Balancer Simulation | simulate_load_balancer | You are given a list of incoming requests and a fixed number of identical servers. Each request is represented as a tuple (arrival_time, load) where:
- `arrival_time` is a nonβnegative integer denoting the time at which the request arrives.
- `load` is a positive integer denoting how much processing load the request ad... | import heapq
from typing import List, Tuple
def simulate_load_balancer(arrivals: List[Tuple[int, int]], k: int) -> List[int]:
"""Return the server index assigned to each request.
Args:
arrivals: List of (arrival_time, load) tuples, sorted by arrival_time.
k: Number of servers.
Returns:
... | import heapq
from typing import List, Tuple
def simulate_load_balancer(arrivals: List[Tuple[int, int]], k: int) -> List[int]:
if not arrivals:
return []
# We need to track the current load of each server.
# We use a min-heap to efficiently find the server with minimal load.
# The heap will... | def check(candidate):
assert candidate(*([(0, 5), (1, 3), (1, 2), (3, 4)], 2)) == [0, 1, 1, 0]
assert candidate(*([(0, 1), (2, 2), (5, 3)], 1)) == [0, 0, 0]
assert candidate(*([], 4)) == []
assert candidate(*([(0, 10), (0, 20)], 5)) == [0, 1]
assert candidate(*([(0, 2), (0, 2), (0, 2), (0, 2)], 2)) ... | 9 | 11 | 20 | 11 | 23 | openai/gpt-oss-120b | qwen/qwen3.6-35b-a3b | train |
Flintglass PrismCode-Hard-Corpus
2,210 Dual-Model Differential-Oracle & Live-Python-Execution Verified Algorithmic & Software Engineering Tasks containing 48,827 live-verified unit & adversarial edge-case assertions (22.09 avg assertions per task, 39.4 avg lines of code) across 10 Real-World SE & Algorithmic Categories & 50 Subcategories β 100% Apache-2.0, zero proprietary API distillation.
Part of the Flintglass Prism Open-Source Agent & RAG Stack.
Why PrismCode-Hard-Corpus?
Synthetic coding datasets frequently suffer from two fatal flaws: (1) LLM-hallucinated test assertions (where a single model guesses wrong expected outputs in its head), and (2) underspecified problem statements (where edge cases or tie-breaking rules are ambiguous, breaking RLVR/GRPO reward signals).
PrismCode-Hard-Corpus eliminates both flaws using a Live Differential Execution Oracle powered exclusively by two distinct Apache-2.0 frontier architectures:
- Specification & Canonical Generator (
openai/gpt-oss-120b, Apache-2.0): Writes an original, self-contained Python specification (prompt+entry_point), a clean stdlib-onlycanonical_solution, andmake_inputs()returning 10β14 diverse argument tuples. - Independent Blind Solver & Adversarial Input Fuzzer (
qwen/qwen3.6-35b-a3b, Apache-2.0): Reads ONLYpromptandentry_point(never seescanonical_solutionormake_inputs) and writes an independent implementation (independent_solution) plusmake_edge_inputs()targeting tricky edge cases (empty inputs, single elements, ties, negatives, duplicates, boundary sizes). - 7-Gate Live Isolated Subprocess Verification (
python3 -I, 512 MB cap, strict stdlib AST audit):- Both solutions and input generators pass static AST safety checks (zero
os/sys/subprocess/network/file I/O). - Both
canonical_solution(*args)andindependent_solution(*args)are executed live on every deduplicated input frommake_inputs() + make_edge_inputs()(using deep copies so mutations cannot leak). - A task is KEPT ONLY IF both independent models agree 100% bit-for-bit (exact value AND exact Python type) across all executed inputs (
>= 12distinct inputs,>= 6unit +>= 4adversarial edge inputs,>= 3distinct outputs) β automatically rejecting ambiguous specifications and buggy solutions (25.9%strict pass rate across7,787candidates!). - Compiled
def check(candidate):suites are re-verified in fresh isolated subprocesses:canonical_solutionPASSES,independent_solutionPASSES, and a dummyreturn Nonestub FAILS.
- Both solutions and input generators pass static AST safety checks (zero
Dataset Statistics
| Split | Verified Tasks | Live-Verified Assertions | Avg Assertions / Task | OOD Subcategory Tasks | Prompt Overlap |
|---|---|---|---|---|---|
train |
1,689 | 37,212 | 22.03 | 0 | 0 |
validation |
153 | 3,401 | 22.23 | 0 | 0 |
hard_test |
368 | 8,214 | 22.32 | 243 (66.0%) | 0 |
| Total | 2,210 | 48,827 | 22.09 | 243 | 0 |
Breakdown by Category (10 SE & Algorithmic Domains, 50 Subcategories)
| Category | Verified Tasks |
|---|---|
binary_search_and_greedy (parametric binary search, multi-server simulation, water-filling) |
435 |
state_machines_and_systems (workflow engines, consistent hashing, vector clocks, memory allocators) |
306 |
business_logic_and_fintech (SaaS proration, tax brackets, FX graphs, FIFO/LIFO COGS, rate limiters) |
272 |
dynamic_programming (interval DP, 2D grid constraints, knapsack, string DP, bitmask/tree DP) |
269 |
math_and_combinatorics (modular arithmetic, matrix exp, exact rationals, 2D integer geometry) |
246 |
graph_and_network_algorithms (constrained Dijkstra, DAG critical path, bridges, MST, SCC) |
201 |
strings_and_text_processing (tokenizers, LZ/RLE codecs, diffs, RFC-4180 CSV, glob matching) |
197 |
parsing_and_compilers (expression evaluators, cron matchers, filter DSLs, semver conflict resolvers) |
114 |
data_structures_and_heaps (LRU/LFU/TTL caches, streaming median, sweep-line, tries, order books) |
90 |
data_engineering_and_pipelines (JSON diff/flatten, time-series resampling, in-memory SQL/CDC, ETL lineage) |
80 |
Breakdown by Difficulty
| Difficulty | Tasks |
|---|---|
medium |
848 (38.4%) |
medium-hard |
717 (32.4%) |
hard |
645 (29.2%) |
- 10 Held-Out OOD Subcategories (exclusively in
hard_test): Bipartite Matching/SCC, Tree/Bitmask DP, Limit/Market Order-Book Engine, Semver Dependency Conflict Resolver, Glob/URL Normalizer, Fair Water-Filling Allocation, DAG ETL Column Lineage, Token-Bucket/Sliding-Window Rate Limiter, Discrete State Recurrence Solver, and Circuit-Breaker/Backoff State Machine.
Schema
Each JSONL row contains:
task_id: Unique ID (pc-XXXXX)split:train,validation, orhard_testcategory,subcategory,is_ood_subcategory,difficultytitle,entry_point,promptcanonical_solution: Verified stdlib-only Python solution (openai/gpt-oss-120b)independent_solution: Second independently verified stdlib-only solution (qwen/qwen3.6-35b-a3b)test: Executabledef check(candidate):test harness containing all live-verified unit + adversarial assertionsnum_unit_tests,num_adversarial_tests,total_asserts,distinct_outputs,solution_linesgenerator_model,cross_verifier_model
Quickstart (Evaluating Any Model / RLVR Reward Function)
from datasets import load_dataset
import subprocess, sys
ds = load_dataset("flintglass/PrismCode-Hard-Corpus")
task = ds["hard_test"][0]
# Run the live differential-verified test harness on a candidate solution
harness = f"{task['canonical_solution']}\n\n{task['test']}\n\ncheck({task['entry_point']})\nprint('PASS')"
res = subprocess.run([sys.executable, "-I", "-c", harness], capture_output=True, text=True, timeout=5)
assert res.returncode == 0 and "PASS" in res.stdout
print(f"Passed all {task['total_asserts']} verified assertions for {task['entry_point']}!")
Related Flintglass Models & Hard Corpora
- Execution-Verified Coding Models: PrismCode-27B, PrismCode-35B-A3B, GPT-OSS-20B-PrismCode, Inkling-2-Mini-PrismCode (+ verified
-GGUFrepos!) - Other Flintglass Hard Verification Corpora: PrismSQL-Hard-Corpus, PrismMCP-Agent-Corpus, PrismVerify-Hard-Corpus, PrismRetrieve-Hard-Corpus
License & Provenance
Released under Apache-2.0 by Flintglass Labs. Generated and cross-verified via live Python differential execution exclusively using Apache-2.0 open-weight models (openai/gpt-oss-120b and qwen/qwen3.6-35b-a3b). Zero proprietary API distillation.
π 12-Model Open-Weight Reference Leaderboard (hard_test)
Evaluated deterministically (zero LLM-as-a-judge) on the exact hard_test split. Explore interactive breakdowns & all 5 OOD suites live on flintglass/PrismBench-Leaderboard.
βdenotes models from the Apache-2.0 dual-model generation/verification family.
| Rank | Model | License | Live Python pass@1 |
OOD Subcategory pass@1 |
|---|---|---|---|---|
| 1 | Gemma-4-31B-IT | Apache-2.0 | 90.76% | 91.36% |
| 2 | GPT-OSS-120B β | Apache-2.0 | 89.95% | 90.12% |
| 3 | GPT-OSS-20B (Base) | Apache-2.0 | 85.87% | 85.60% |
| 4 | Qwen3.6-35B-A3B β | Apache-2.0 | 83.15% | 83.54% |
| 5 | DeepSeek-V3.2 | MIT | 83.15% | 81.89% |
| 6 | Qwen3.8-27B (Base) | Apache-2.0 | 81.25% | 81.07% |
| 7 | Gemma-4-26B-A4B-IT | Apache-2.0 | 78.80% | 78.60% |
| 8 | Mistral-Small-2603 (24B) | Apache-2.0 | 69.57% | 70.78% |
| 9 | Qwen3-Coder-30B-A3B | Apache-2.0 | 67.93% | 67.90% |
| 10 | Qwen3.5-9B (Base) | Apache-2.0 | 64.40% | 64.61% |
| 11 | Llama-3.3-70B-Instruct | Llama-3.3 | 57.34% | 56.38% |
| 12 | DeepSeek-V4.1-Flash | MIT | 19.57% | 18.52% |
- Downloads last month
- -