File size: 17,946 Bytes
9580dce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 | import type {
CodingProblem,
CodingProblemType,
CodingDifficulty,
CodingLanguage,
} from "./types";
import { isExecutableType } from "./types";
// ---------------------------------------------------------------------------
// Curated problem bank β the verified source of truth.
//
// Every entry is checked by validateProblem() in bank.test.ts, so the bank is
// guaranteed to have known, verifiable answers: reference solutions pass their
// own tests, buggy snippets actually fail, review issues are well-formed, and
// architecture rubrics are non-empty. This is what makes Coding Training work
// fully offline / local-first; LLM generation (when an API key is present)
// adds variety on top, falling back to the bank on any failure.
// ---------------------------------------------------------------------------
export const PROBLEM_BANK: CodingProblem[] = [
// βββ code-creation (JavaScript) βββββββββββββββββββββββββββββββββββββββββ
{
id: "cc-js-easy-sum-evens",
type: "code-creation",
language: "javascript",
difficulty: "easy",
title: "Sum of Even Numbers",
prompt:
"Implement `sumOfEvens(nums)` which returns the sum of all even numbers in the array `nums`. Return 0 if there are none.",
entryFunction: "sumOfEvens",
starterCode:
"function sumOfEvens(nums) {\n // your code here\n}\n",
referenceSolution:
"function sumOfEvens(nums) {\n return nums.filter((n) => n % 2 === 0).reduce((a, b) => a + b, 0);\n}\n",
tests: [
{ name: "mixed", input: [[1, 2, 3, 4]], expected: 6 },
{ name: "all even", input: [[2, 4, 6]], expected: 12 },
{ name: "no evens", input: [[1, 3, 5]], expected: 0, hidden: true },
{ name: "empty", input: [[]], expected: 0, hidden: true },
{ name: "negatives", input: [[-2, -4, 1]], expected: -6, hidden: true },
],
},
{
id: "cc-js-easy-reverse",
type: "code-creation",
language: "javascript",
difficulty: "easy",
title: "Reverse a String",
prompt:
"Implement `reverse(s)` which returns the string `s` reversed.",
entryFunction: "reverse",
starterCode: "function reverse(s) {\n // your code here\n}\n",
referenceSolution:
"function reverse(s) {\n return s.split('').reverse().join('');\n}\n",
tests: [
{ name: "word", input: ["hello"], expected: "olleh" },
{ name: "empty", input: [""], expected: "", hidden: true },
{ name: "palindrome", input: ["aba"], expected: "aba", hidden: true },
],
},
{
id: "cc-js-medium-two-sum",
type: "code-creation",
language: "javascript",
difficulty: "medium",
title: "Two Sum",
prompt:
"Implement `twoSum(nums, target)`. Return the indices `[i, j]` of the two numbers that add up to `target` (exactly one solution exists; `i < j`). Return `[]` if none.",
entryFunction: "twoSum",
starterCode:
"function twoSum(nums, target) {\n // your code here\n}\n",
referenceSolution:
"function twoSum(nums, target) {\n const seen = new Map();\n for (let i = 0; i < nums.length; i++) {\n const need = target - nums[i];\n if (seen.has(need)) return [seen.get(need), i];\n seen.set(nums[i], i);\n }\n return [];\n}\n",
tests: [
{ name: "basic", input: [[2, 7, 11, 15], 9], expected: [0, 1] },
{ name: "middle", input: [[3, 2, 4], 6], expected: [1, 2] },
{ name: "dupes", input: [[3, 3], 6], expected: [0, 1], hidden: true },
{ name: "none", input: [[1, 2, 3], 7], expected: [], hidden: true },
],
},
{
id: "cc-js-medium-balanced",
type: "code-creation",
language: "javascript",
difficulty: "medium",
title: "Balanced Brackets",
prompt:
"Implement `isBalanced(s)` that returns true if every bracket in `s` (`()`, `[]`, `{}`) is correctly opened and closed in order.",
entryFunction: "isBalanced",
starterCode:
"function isBalanced(s) {\n // your code here\n}\n",
referenceSolution:
"function isBalanced(s) {\n const pairs = { ')': '(', ']': '[', '}': '{' };\n const stack = [];\n for (const ch of s) {\n if (ch === '(' || ch === '[' || ch === '{') stack.push(ch);\n else if (pairs[ch]) {\n if (stack.pop() !== pairs[ch]) return false;\n }\n }\n return stack.length === 0;\n}\n",
tests: [
{ name: "simple", input: ["()"], expected: true },
{ name: "nested", input: ["{[()]}"], expected: true },
{ name: "wrong order", input: ["(]"], expected: false, hidden: true },
{ name: "unclosed", input: ["((("], expected: false, hidden: true },
{ name: "text ok", input: ["a(b)c"], expected: true, hidden: true },
],
},
{
id: "cc-js-hard-longest-substring",
type: "code-creation",
language: "javascript",
difficulty: "hard",
title: "Longest Substring Without Repeating Characters",
prompt:
"Implement `lengthOfLongestSubstring(s)` returning the length of the longest substring of `s` with all distinct characters.",
entryFunction: "lengthOfLongestSubstring",
starterCode:
"function lengthOfLongestSubstring(s) {\n // your code here\n}\n",
referenceSolution:
"function lengthOfLongestSubstring(s) {\n const seen = new Set();\n let left = 0;\n let best = 0;\n for (let right = 0; right < s.length; right++) {\n while (seen.has(s[right])) {\n seen.delete(s[left]);\n left++;\n }\n seen.add(s[right]);\n best = Math.max(best, right - left + 1);\n }\n return best;\n}\n",
tests: [
{ name: "abcabcbb", input: ["abcabcbb"], expected: 3 },
{ name: "bbbbb", input: ["bbbbb"], expected: 1 },
{ name: "pwwkew", input: ["pwwkew"], expected: 3, hidden: true },
{ name: "empty", input: [""], expected: 0, hidden: true },
{ name: "dvdf", input: ["dvdf"], expected: 3, hidden: true },
],
},
// βββ debugging (JavaScript) βββββββββββββββββββββββββββββββββββββββββββββ
{
id: "db-js-easy-factorial",
type: "debugging",
language: "javascript",
difficulty: "easy",
title: "Broken Factorial",
prompt:
"`factorial(n)` should return n!. It currently returns 0 for every input. Find and fix the bug so all tests pass.",
entryFunction: "factorial",
buggyCode:
"function factorial(n) {\n let result = 0;\n for (let i = 1; i <= n; i++) {\n result *= i;\n }\n return result;\n}\n",
referenceSolution:
"function factorial(n) {\n let result = 1;\n for (let i = 1; i <= n; i++) {\n result *= i;\n }\n return result;\n}\n",
tests: [
{ name: "0!", input: [0], expected: 1 },
{ name: "5!", input: [5], expected: 120 },
{ name: "1!", input: [1], expected: 1, hidden: true },
{ name: "4!", input: [4], expected: 24, hidden: true },
],
},
{
id: "db-js-medium-binary-search",
type: "debugging",
language: "javascript",
difficulty: "medium",
title: "Off-by-one Binary Search",
prompt:
"`binarySearch(arr, target)` should return the index of `target` in the sorted array `arr`, or -1. It misses elements at the boundary. Fix it.",
entryFunction: "binarySearch",
buggyCode:
"function binarySearch(arr, target) {\n let lo = 0;\n let hi = arr.length - 1;\n while (lo < hi) {\n const mid = Math.floor((lo + hi) / 2);\n if (arr[mid] === target) return mid;\n if (arr[mid] < target) lo = mid + 1;\n else hi = mid - 1;\n }\n return -1;\n}\n",
referenceSolution:
"function binarySearch(arr, target) {\n let lo = 0;\n let hi = arr.length - 1;\n while (lo <= hi) {\n const mid = Math.floor((lo + hi) / 2);\n if (arr[mid] === target) return mid;\n if (arr[mid] < target) lo = mid + 1;\n else hi = mid - 1;\n }\n return -1;\n}\n",
tests: [
{ name: "found middle", input: [[1, 2, 3, 4, 5], 4], expected: 3 },
{ name: "last element", input: [[1, 2, 3], 3], expected: 2, hidden: true },
{ name: "first element", input: [[1, 2, 3], 1], expected: 0 },
{ name: "single", input: [[5], 5], expected: 0, hidden: true },
{ name: "missing", input: [[1, 2, 3], 9], expected: -1, hidden: true },
],
},
{
id: "db-js-hard-max-subarray",
type: "debugging",
language: "javascript",
difficulty: "hard",
title: "Kadane's Algorithm Fails on Negatives",
prompt:
"`maxSubArray(nums)` should return the largest sum of any contiguous subarray. It returns 0 when all numbers are negative. Fix the initialization bug.",
entryFunction: "maxSubArray",
buggyCode:
"function maxSubArray(nums) {\n let best = 0;\n let cur = 0;\n for (const n of nums) {\n cur = Math.max(n, cur + n);\n best = Math.max(best, cur);\n }\n return best;\n}\n",
referenceSolution:
"function maxSubArray(nums) {\n let best = -Infinity;\n let cur = 0;\n for (const n of nums) {\n cur = Math.max(n, cur + n);\n best = Math.max(best, cur);\n }\n return best;\n}\n",
tests: [
{ name: "mixed", input: [[-2, 1, -3, 4, -1, 2, 1, -5, 4]], expected: 6 },
{ name: "all negative", input: [[-1, -2, -3]], expected: -1, hidden: true },
{ name: "single", input: [[1]], expected: 1 },
{ name: "all positive", input: [[5, 4, -1, 7, 8]], expected: 23, hidden: true },
],
},
// βββ code-review ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
{
id: "cr-js-easy-clean-clamp",
type: "code-review",
language: "javascript",
difficulty: "easy",
title: "Review: clamp()",
prompt:
"An AI assistant produced the function below. Review it and list any bugs or issues β or state that it is correct. Be precise.",
code:
"function clamp(value, min, max) {\n if (value < min) return min;\n if (value > max) return max;\n return value;\n}\n",
issues: [], // intentionally clean: tests the 0-issue path
},
{
id: "cr-js-medium-average",
type: "code-review",
language: "javascript",
difficulty: "medium",
title: "Review: average()",
prompt:
"An AI assistant wrote `average(scores)` to compute the mean of an array. Review it for correctness and edge cases. List every issue you find.",
code:
"function average(scores) {\n let total = 0;\n for (let i = 0; i <= scores.length; i++) {\n total += scores[i];\n }\n return total / scores.length;\n}\n",
issues: [
{
id: "off-by-one",
title: "Loop overruns the array",
description:
"The loop condition `i <= scores.length` reads one past the end of the array, adding `undefined` and turning the total into NaN.",
severity: "critical",
line: 3,
},
{
id: "empty-divide",
title: "Division by zero on empty input",
description:
"When `scores` is empty, `total / scores.length` divides by zero and returns NaN; there is no guard for the empty case.",
severity: "minor",
line: 6,
},
],
},
{
id: "cr-js-hard-fetch-user",
type: "code-review",
language: "javascript",
difficulty: "hard",
title: "Review: getUserName()",
prompt:
"Review this AI-generated lookup helper. Identify any correctness or robustness issues.",
code:
"function getUserName(users, id) {\n const user = users.find((u) => u.id == id);\n return user.name;\n}\n",
issues: [
{
id: "missing-null-check",
title: "No null check on the lookup result",
description:
"`find` returns undefined when no user matches, so `user.name` throws a TypeError. The function should handle the not-found case.",
severity: "major",
line: 3,
},
{
id: "loose-equality",
title: "Loose equality (==) for id comparison",
description:
"`u.id == id` uses loose equality and can match across types (e.g. number 1 vs string '1'), causing subtle bugs. Use === with consistent types.",
severity: "minor",
line: 2,
},
],
},
{
id: "cr-py-medium-get-first",
type: "code-review",
language: "python",
difficulty: "medium",
title: "Review: get_first()",
prompt:
"An AI wrote this Python helper to return the first item of a list. Review it for issues.",
code:
"def get_first(items):\n return items[0]\n",
issues: [
{
id: "index-error",
title: "IndexError on empty list",
description:
"Indexing `items[0]` raises IndexError when the list is empty. The function should return a default or handle the empty case.",
severity: "major",
line: 2,
},
],
},
// βββ architecture βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
{
id: "ar-easy-todo-api",
type: "architecture",
language: "javascript",
difficulty: "easy",
title: "Design a TODO list REST API",
prompt:
"Design a small REST API for a single-user TODO list. Describe the resources/endpoints, the data model, and how you'd persist the data. Mention one tradeoff you considered.",
rubric: [
{ id: "endpoints", point: "Defines CRUD endpoints / HTTP verbs for todo items", weight: 2 },
{ id: "model", point: "Specifies a data model (id, title, completed, timestamps)", weight: 1 },
{ id: "persistence", point: "Chooses a persistence layer and justifies it", weight: 1 },
{ id: "tradeoff", point: "Articulates at least one design tradeoff", weight: 1 },
],
},
{
id: "ar-medium-rate-limiter",
type: "architecture",
language: "javascript",
difficulty: "medium",
title: "Design an API Rate Limiter",
prompt:
"Design a rate limiter for a public HTTP API (e.g. 100 requests/min per API key). Discuss the algorithm, where state lives, how it behaves under bursts, and what happens when the limiter's backing store is unavailable.",
rubric: [
{ id: "algorithm", point: "Selects an algorithm (token bucket / sliding window / fixed window) and explains it", weight: 2 },
{ id: "granularity", point: "Defines the limit key/granularity (per API key / IP / user)", weight: 1 },
{ id: "state", point: "Decides where counters live (in-memory vs shared store like Redis) and why", weight: 2 },
{ id: "bursts", point: "Addresses burst handling / smoothing", weight: 1 },
{ id: "failure", point: "Considers failure mode when the backing store is down (fail-open vs fail-closed)", weight: 1 },
],
},
{
id: "ar-hard-url-shortener",
type: "architecture",
language: "javascript",
difficulty: "hard",
title: "Design a URL Shortener",
prompt:
"Design a URL shortener (like bit.ly) that must handle high read volume. Cover short-code generation, collision handling, storage, how you scale reads, and one operational concern (analytics, expiry, or abuse).",
rubric: [
{ id: "keygen", point: "Describes short-code generation (hashing, counter+base62, or random) ", weight: 2 },
{ id: "collisions", point: "Handles collisions / uniqueness guarantees", weight: 1 },
{ id: "storage", point: "Chooses a storage/DB and key-value access pattern", weight: 1 },
{ id: "read-scale", point: "Scales reads (caching / CDN / replicas) given read-heavy load", weight: 2 },
{ id: "ops", point: "Addresses an operational concern (analytics, expiry, or abuse prevention)", weight: 1 },
],
},
];
// ---------------------------------------------------------------------------
// Selection
// ---------------------------------------------------------------------------
export interface PickOptions {
type: CodingProblemType;
difficulty: CodingDifficulty;
language: CodingLanguage;
/** When true, never substitute a different language β return null instead. */
strictLanguage?: boolean;
/** Injectable RNG for deterministic selection in tests. */
rng?: () => number;
}
/**
* Pick a problem matching the requested type + difficulty. Prefers an exact
* language match; otherwise (unless strictLanguage) falls back to a JavaScript
* executable problem for executable types, or any-language problem for written
* types. Returns null when nothing fits.
*/
export function pickProblem(opts: PickOptions): CodingProblem | null {
const rng = opts.rng ?? Math.random;
const byTypeDiff = PROBLEM_BANK.filter(
(p) => p.type === opts.type && p.difficulty === opts.difficulty,
);
if (byTypeDiff.length === 0) return null;
const exact = byTypeDiff.filter((p) => p.language === opts.language);
if (exact.length > 0) return choose(exact, rng);
if (opts.strictLanguage) return null;
const fallback = isExecutableType(opts.type)
? byTypeDiff.filter((p) => p.language === "javascript")
: byTypeDiff;
if (fallback.length === 0) return null;
return choose(fallback, rng);
}
function choose<T>(items: T[], rng: () => number): T {
const idx = Math.min(items.length - 1, Math.floor(rng() * items.length));
return items[idx];
}
// ---------------------------------------------------------------------------
// Stats (used by the generate route metadata / UI)
// ---------------------------------------------------------------------------
export function bankStats(): {
total: number;
byType: Record<CodingProblemType, number>;
} {
const byType = {
"code-creation": 0,
debugging: 0,
"code-review": 0,
architecture: 0,
} as Record<CodingProblemType, number>;
for (const p of PROBLEM_BANK) byType[p.type]++;
return { total: PROBLEM_BANK.length, byType };
}
|