[
  {
    "id": "task_01",
    "title": "Search in Rotated Sorted Array",
    "category": "Algorithms & Data Structures",
    "language": "python",
    "prompt": "Write a Python function `search_rotated(nums: list[int], target: int) -> int` that searches for a target value in a sorted array that has been rotated at some pivot unknown beforehand. Return the 0-based index if found, or -1 if not found. Must achieve O(log n) runtime complexity.",
    "signature": "def search_rotated(nums: list[int], target: int) -> int:",
    "test_cases": [
      {
        "input": [
          [
            4,
            5,
            6,
            7,
            0,
            1,
            2
          ],
          0
        ],
        "expected": 4
      },
      {
        "input": [
          [
            4,
            5,
            6,
            7,
            0,
            1,
            2
          ],
          3
        ],
        "expected": -1
      },
      {
        "input": [
          [
            1
          ],
          0
        ],
        "expected": -1
      },
      {
        "input": [
          [
            1
          ],
          1
        ],
        "expected": 0
      },
      {
        "input": [
          [
            5,
            1,
            3
          ],
          5
        ],
        "expected": 0
      }
    ],
    "reference_solution": "def search_rotated(nums, target):\n    if not nums: return -1\n    low, high = 0, len(nums) - 1\n    while low <= high:\n        mid = (low + high) // 2\n        if nums[mid] == target:\n            return mid\n        if nums[low] <= nums[mid]:\n            if nums[low] <= target < nums[mid]:\n                high = mid - 1\n            else:\n                low = mid + 1\n        else:\n            if nums[mid] < target <= nums[high]:\n                low = mid + 1\n            else:\n                high = mid - 1\n    return -1"
  },
  {
    "id": "task_02",
    "title": "LRU Cache Implementation",
    "category": "Algorithms & Data Structures",
    "language": "python",
    "prompt": "Implement a `LRUCache` class with `__init__(self, capacity: int)`, `get(self, key: int) -> int`, and `put(self, key: int, value: int) -> None`. `get` and `put` must both operate in O(1) average time complexity. If key is not found, `get` returns -1.",
    "signature": "class LRUCache:",
    "test_cases": [
      {
        "operations": [
          "put(1, 1)",
          "put(2, 2)",
          "get(1)",
          "put(3, 3)",
          "get(2)",
          "put(4, 4)",
          "get(1)",
          "get(3)",
          "get(4)"
        ],
        "expected": [
          null,
          null,
          1,
          null,
          -1,
          null,
          -1,
          3,
          4
        ]
      }
    ],
    "reference_solution": "from collections import OrderedDict\n\nclass LRUCache:\n    def __init__(self, capacity: int):\n        self.cap = capacity\n        self.cache = OrderedDict()\n\n    def get(self, key: int) -> int:\n        if key not in self.cache:\n            return -1\n        self.cache.move_to_end(key)\n        return self.cache[key]\n\n    def put(self, key: int, value: int) -> None:\n        if key in self.cache:\n            self.cache.move_to_end(key)\n        self.cache[key] = value\n        if len(self.cache) > self.cap:\n            self.cache.popitem(last=False)"
  },
  {
    "id": "task_03",
    "title": "Trie Prefix Search and Autocomplete",
    "category": "Algorithms & Data Structures",
    "language": "python",
    "prompt": "Implement a `Trie` class with methods `insert(self, word: str) -> None`, `search(self, word: str) -> bool`, and `starts_with(self, prefix: str) -> bool`.",
    "signature": "class Trie:",
    "test_cases": [
      {
        "operations": [
          "insert('apple')",
          "search('apple')",
          "search('app')",
          "starts_with('app')",
          "insert('app')",
          "search('app')"
        ],
        "expected": [
          null,
          true,
          false,
          true,
          null,
          true
        ]
      }
    ],
    "reference_solution": "class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.is_end = False\n\nclass Trie:\n    def __init__(self):\n        self.root = TrieNode()\n\n    def insert(self, word: str) -> None:\n        node = self.root\n        for ch in word:\n            if ch not in node.children:\n                node.children[ch] = TrieNode()\n            node = node.children[ch]\n        node.is_end = True\n\n    def search(self, word: str) -> bool:\n        node = self.root\n        for ch in word:\n            if ch not in node.children:\n                return False\n            node = node.children[ch]\n        return node.is_end\n\n    def starts_with(self, prefix: str) -> bool:\n        node = self.root\n        for ch in prefix:\n            if ch not in node.children:\n                return False\n            node = node.children[ch]\n        return True"
  },
  {
    "id": "task_04",
    "title": "Merge Overlapping Intervals",
    "category": "Algorithms & Data Structures",
    "language": "python",
    "prompt": "Write a Python function `merge_intervals(intervals: list[list[int]]) -> list[list[int]]` that merges all overlapping intervals into a list of non-overlapping intervals covering all the intervals in the input.",
    "signature": "def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:",
    "test_cases": [
      {
        "input": [
          [
            [
              1,
              3
            ],
            [
              2,
              6
            ],
            [
              8,
              10
            ],
            [
              15,
              18
            ]
          ]
        ],
        "expected": [
          [
            1,
            6
          ],
          [
            8,
            10
          ],
          [
            15,
            18
          ]
        ]
      },
      {
        "input": [
          [
            [
              1,
              4
            ],
            [
              4,
              5
            ]
          ]
        ],
        "expected": [
          [
            1,
            5
          ]
        ]
      },
      {
        "input": [
          [

          ]
        ],
        "expected": [

        ]
      },
      {
        "input": [
          [
            [
              1,
              4
            ],
            [
              0,
              4
            ]
          ]
        ],
        "expected": [
          [
            0,
            4
          ]
        ]
      }
    ],
    "reference_solution": "def merge_intervals(intervals):\n    if not intervals: return []\n    intervals.sort(key=lambda x: x[0])\n    merged = [intervals[0]]\n    for current in intervals[1:]:\n        prev = merged[-1]\n        if current[0] <= prev[1]:\n            prev[1] = max(prev[1], current[1])\n        else:\n            merged.append(current)\n    return merged"
  },
  {
    "id": "task_05",
    "title": "Valid Parentheses with Multiple Brackets",
    "category": "Algorithms & Data Structures",
    "language": "python",
    "prompt": "Write a Python function `is_valid_brackets(s: str) -> bool` determining if an input string containing '(', ')', '{', '}', '[' and ']' has all opening brackets closed by the same type of brackets in the correct order.",
    "signature": "def is_valid_brackets(s: str) -> bool:",
    "test_cases": [
      {
        "input": [
          "()[]{}"
        ],
        "expected": true
      },
      {
        "input": [
          "(]"
        ],
        "expected": false
      },
      {
        "input": [
          "([)]"
        ],
        "expected": false
      },
      {
        "input": [
          "{[]}"
        ],
        "expected": true
      },
      {
        "input": [
          ""
        ],
        "expected": true
      }
    ],
    "reference_solution": "def is_valid_brackets(s: str) -> bool:\n    stack = []\n    mapping = {')': '(', '}': '{', ']': '['}\n    for char in s:\n        if char in mapping:\n            top = stack.pop() if stack else '#'\n            if mapping[char] != top:\n                return False\n        else:\n            stack.append(char)\n    return not stack"
  },
  {
    "id": "task_06",
    "title": "Semantic Versioning Comparator",
    "category": "String & Regex Parsing",
    "language": "python",
    "prompt": "Write a Python function `compare_semver(v1: str, v2: str) -> int` that compares two SemVer strings (e.g. '1.2.3', '1.2.3-alpha.1'). Return 1 if v1 > v2, -1 if v1 < v2, and 0 if v1 == v2. Handle standard major.minor.patch and pre-release tags per SemVer 2.0.0 specification.",
    "signature": "def compare_semver(v1: str, v2: str) -> int:",
    "test_cases": [
      {
        "input": [
          "1.0.0",
          "2.0.0"
        ],
        "expected": -1
      },
      {
        "input": [
          "2.1.0",
          "2.0.1"
        ],
        "expected": 1
      },
      {
        "input": [
          "1.0.0-alpha",
          "1.0.0"
        ],
        "expected": -1
      },
      {
        "input": [
          "1.0.0-alpha.1",
          "1.0.0-alpha.2"
        ],
        "expected": -1
      },
      {
        "input": [
          "1.2.3",
          "1.2.3"
        ],
        "expected": 0
      }
    ],
    "reference_solution": "import re\n\ndef compare_semver(v1: str, v2: str) -> int:\n    def parse(v):\n        parts = v.split('-', 1)\n        nums = [int(x) for x in parts[0].split('.')]\n        prerelease = parts[1] if len(parts) > 1 else None\n        return nums, prerelease\n\n    n1, p1 = parse(v1)\n    n2, p2 = parse(v2)\n    if n1 != n2:\n        return 1 if n1 > n2 else -1\n    if p1 is None and p2 is not None: return 1\n    if p1 is not None and p2 is None: return -1\n    if p1 == p2: return 0\n    return 1 if p1 > p2 else -1"
  },
  {
    "id": "task_07",
    "title": "Markdown Link and Image Extractor",
    "category": "String & Regex Parsing",
    "language": "python",
    "prompt": "Write a Python function `extract_markdown_media(markdown_text: str) -> dict` returning a dictionary with keys 'links' and 'images'. 'links' should be a list of tuples `(text, url)` for standard hyperlinks `[text](url)`. 'images' should be a list of tuples `(alt_text, url)` for images `![alt](url)`. Do not confuse images with regular links.",
    "signature": "def extract_markdown_media(markdown_text: str) -> dict:",
    "test_cases": [
      {
        "input": [
          "Read the [docs](https://openrouter.ai/docs) and view ![Architecture Diagram](https://openrouter.ai/arch.png)."
        ],
        "expected": {
          "links": [
            [
              "docs",
              "https://openrouter.ai/docs"
            ]
          ],
          "images": [
            [
              "Architecture Diagram",
              "https://openrouter.ai/arch.png"
            ]
          ]
        }
      }
    ],
    "reference_solution": "import re\n\ndef extract_markdown_media(text: str) -> dict:\n    images = re.findall(r'!\\[([^\\]]*)\\]\\(([^\\)]+)\\)', text)\n    text_no_images = re.sub(r'!\\[[^\\]]*\\]\\([^\\)]+\\)', '', text)\n    links = re.findall(r'\\[([^\\]]+)\\]\\(([^\\)]+)\\)', text_no_images)\n    return {'links': links, 'images': images}"
  },
  {
    "id": "task_08",
    "title": "Nginx Access Log Parser",
    "category": "String & Regex Parsing",
    "language": "python",
    "prompt": "Write a Python function `parse_nginx_log(log_line: str) -> dict` that parses a Combined Log Format line into a dict with keys: 'ip', 'timestamp', 'method', 'path', 'status', 'bytes_sent', 'referrer', 'user_agent'.",
    "signature": "def parse_nginx_log(log_line: str) -> dict:",
    "test_cases": [
      {
        "input": [
          "192.168.1.1 - - [20/Sep/2026:14:32:10 +0000] \"GET /api/v1/models HTTP/1.1\" 200 4521 \"https://vibecoderjournal.com\" \"Mozilla/5.0\""
        ],
        "expected": {
          "ip": "192.168.1.1",
          "timestamp": "20/Sep/2026:14:32:10 +0000",
          "method": "GET",
          "path": "/api/v1/models",
          "status": 200,
          "bytes_sent": 4521,
          "referrer": "https://vibecoderjournal.com",
          "user_agent": "Mozilla/5.0"
        }
      }
    ],
    "reference_solution": "import re\n\ndef parse_nginx_log(log_line: str) -> dict:\n    pattern = r'^(\\S+) \\S+ \\S+ \\[(.*?)\\] \"(\\S+) (\\S+) \\S+\" (\\d{3}) (\\d+) \"(.*?)\" \"(.*?)\"'\n    m = re.match(pattern, log_line)\n    if not m: return {}\n    ip, ts, method, path, st, bytes_sent, ref, ua = m.groups()\n    return {'ip': ip, 'timestamp': ts, 'method': method, 'path': path, 'status': int(st), 'bytes_sent': int(bytes_sent), 'referrer': ref, 'user_agent': ua}"
  },
  {
    "id": "task_09",
    "title": "Unicode Slugifier",
    "category": "String & Regex Parsing",
    "language": "python",
    "prompt": "Write a Python function `slugify(text: str) -> str` that converts a string to a clean URL slug: convert to lowercase, normalize accented Unicode characters to ASCII equivalents, replace all non-alphanumeric characters with a single hyphen, and trim leading/trailing hyphens.",
    "signature": "def slugify(text: str) -> str:",
    "test_cases": [
      {
        "input": [
          "Best Free OpenRouter Models (2026 Update!)"
        ],
        "expected": "best-free-openrouter-models-2026-update"
      },
      {
        "input": [
          "Crème Brûlée & Café @ $5"
        ],
        "expected": "creme-brulee-cafe-5"
      },
      {
        "input": [
          "---Hello---World---"
        ],
        "expected": "hello-world"
      }
    ],
    "reference_solution": "import unicodedata, re\n\ndef slugify(text: str) -> str:\n    text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8')\n    text = text.lower()\n    text = re.sub(r'[^a-z0-9]+', '-', text)\n    return text.strip('-')"
  },
  {
    "id": "task_10",
    "title": "JSON Path Simple Query Evaluator",
    "category": "String & Regex Parsing",
    "language": "python",
    "prompt": "Write a Python function `json_get(data: dict, path: str, default=None)` that retrieves a value from a nested dict/list using dot-and-bracket notation like 'models[0].name' or 'data.limits.rpm'. If the path does not exist, return `default`.",
    "signature": "def json_get(data: dict, path: str, default=None):",
    "test_cases": [
      {
        "input": [
          {
            "models": [
              {
                "name": "deepseek-v4",
                "context": 1048576
              }
            ]
          },
          "models[0].name"
        ],
        "expected": "deepseek-v4"
      },
      {
        "input": [
          {
            "limits": {
              "free": {
                "rpm": 20
              }
            }
          },
          "limits.free.rpm"
        ],
        "expected": 20
      },
      {
        "input": [
          {
            "a": 1
          },
          "b.c.d",
          "NOT_FOUND"
        ],
        "expected": "NOT_FOUND"
      }
    ],
    "reference_solution": "import re\n\ndef json_get(data, path, default=None):\n    tokens = re.findall(r'[^\\.\\[\\]]+', path)\n    curr = data\n    for token in tokens:\n        try:\n            if isinstance(curr, list):\n                curr = curr[int(token)]\n            elif isinstance(curr, dict):\n                curr = curr[token]\n            else:\n                return default\n        except (KeyError, IndexError, ValueError, TypeError):\n            return default\n    return curr"
  },
  {
    "id": "task_11",
    "title": "Streaming CSV Quoted Field Splitter",
    "category": "Systems & File I/O",
    "language": "python",
    "prompt": "Write a Python function `split_csv_line(line: str) -> list[str]` that splits a single CSV line into its constituent fields, accurately respecting double-quote encapsulation and escaped quotes `\"\"` within fields.",
    "signature": "def split_csv_line(line: str) -> list[str]:",
    "test_cases": [
      {
        "input": [
          "deepseek/deepseek-chat:free,1048576,\"98.4%\",1.12"
        ],
        "expected": [
          "deepseek/deepseek-chat:free",
          "1048576",
          "98.4%",
          "1.12"
        ]
      },
      {
        "input": [
          "\"Qwen 3.8, 27B\",\"Says \"\"Hello, World!\"\"\",100"
        ],
        "expected": [
          "Qwen 3.8, 27B",
          "Says \"Hello, World!\"",
          "100"
        ]
      }
    ],
    "reference_solution": "import csv, io\n\ndef split_csv_line(line: str) -> list[str]:\n    reader = csv.reader(io.StringIO(line))\n    return next(reader, [])"
  },
  {
    "id": "task_12",
    "title": "Token Bucket Rate Limiter",
    "category": "Systems & File I/O",
    "language": "python",
    "prompt": "Implement a `TokenBucket` class with `__init__(self, capacity: int, refill_rate_per_sec: float)` and `consume(self, tokens: int = 1, current_time: float = None) -> bool`. Tokens accumulate over elapsed time up to capacity. Return True if enough tokens were available and consumed, False otherwise.",
    "signature": "class TokenBucket:",
    "test_cases": [
      {
        "script": "tb = TokenBucket(10, 2.0)\nr1 = tb.consume(5, 0.0)\nr2 = tb.consume(6, 0.0)\nr3 = tb.consume(6, 1.0)\nassert r1 == True and r2 == False and r3 == True"
      }
    ],
    "reference_solution": "import time\n\nclass TokenBucket:\n    def __init__(self, capacity: int, refill_rate_per_sec: float):\n        self.capacity = float(capacity)\n        self.tokens = float(capacity)\n        self.rate = float(refill_rate_per_sec)\n        self.last_check = 0.0\n\n    def consume(self, tokens: int = 1, current_time: float = None) -> bool:\n        if current_time is None:\n            current_time = time.time()\n        elapsed = max(0.0, current_time - self.last_check)\n        self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)\n        self.last_check = current_time\n        if self.tokens >= tokens:\n            self.tokens -= tokens\n            return True\n        return False"
  },
  {
    "id": "task_13",
    "title": "Recursive JSON Deep Merge",
    "category": "Systems & File I/O",
    "language": "python",
    "prompt": "Write a Python function `deep_merge(target: dict, source: dict) -> dict` that recursively merges two dictionaries. If a key exists in both and both values are dictionaries, merge them recursively. If both are lists, concatenate them. Otherwise, overwrite target with source's value. Return the modified target dict.",
    "signature": "def deep_merge(target: dict, source: dict) -> dict:",
    "test_cases": [
      {
        "input": [
          {
            "a": 1,
            "b": {
              "x": 10
            },
            "tags": [
              "ai"
            ]
          },
          {
            "b": {
              "y": 20
            },
            "tags": [
              "coding"
            ],
            "c": 3
          }
        ],
        "expected": {
          "a": 1,
          "b": {
            "x": 10,
            "y": 20
          },
          "tags": [
            "ai",
            "coding"
          ],
          "c": 3
        }
      }
    ],
    "reference_solution": "def deep_merge(target: dict, source: dict) -> dict:\n    for k, v in source.items():\n        if k in target and isinstance(target[k], dict) and isinstance(v, dict):\n            deep_merge(target[k], v)\n        elif k in target and isinstance(target[k], list) and isinstance(v, list):\n            target[k].extend(v)\n        else:\n            target[k] = v\n    return target"
  },
  {
    "id": "task_14",
    "title": "Exponential Backoff with Full Jitter",
    "category": "Systems & File I/O",
    "language": "python",
    "prompt": "Write a Python function `calculate_backoff(attempt: int, base_delay: float = 1.0, max_delay: float = 60.0, seed: int = 42) -> float` that calculates exponential backoff delay with full jitter using a deterministic pseudo-random seed. The delay is chosen uniformly between 0 and min(max_delay, base_delay * 2 ** attempt). Round to 2 decimal places.",
    "signature": "def calculate_backoff(attempt: int, base_delay: float = 1.0, max_delay: float = 60.0, seed: int = 42) -> float:",
    "test_cases": [
      {
        "input": [
          0,
          1.0,
          60.0,
          42
        ],
        "expected": 0.64
      },
      {
        "input": [
          3,
          1.0,
          60.0,
          42
        ],
        "expected": 5.11
      }
    ],
    "reference_solution": "import random\n\ndef calculate_backoff(attempt: int, base_delay: float = 1.0, max_delay: float = 60.0, seed: int = 42) -> float:\n    rnd = random.Random(seed + attempt)\n    cap = min(max_delay, base_delay * (2 ** attempt))\n    return round(rnd.uniform(0, cap), 2)"
  },
  {
    "id": "task_15",
    "title": "In-Memory TTL Cache",
    "category": "Systems & File I/O",
    "language": "python",
    "prompt": "Implement a `TTLCache` class with `set(self, key: str, value, ttl_seconds: float, current_time: float = 0.0)` and `get(self, key: str, current_time: float = 0.0)`. `get` returns the stored value if `current_time < expiry_time`, or None if the item has expired or does not exist.",
    "signature": "class TTLCache:",
    "test_cases": [
      {
        "script": "cache = TTLCache()\ncache.set('k1', 'v1', 5.0, 100.0)\nassert cache.get('k1', 104.0) == 'v1'\nassert cache.get('k1', 105.0) is None\nassert cache.get('unknown', 100.0) is None"
      }
    ],
    "reference_solution": "class TTLCache:\n    def __init__(self):\n        self.store = {}\n\n    def set(self, key: str, value, ttl_seconds: float, current_time: float = 0.0):\n        self.store[key] = (value, current_time + ttl_seconds)\n\n    def get(self, key: str, current_time: float = 0.0):\n        if key not in self.store: return None\n        val, exp = self.store[key]\n        if current_time >= exp:\n            del self.store[key]\n            return None\n        return val"
  },
  {
    "id": "task_16",
    "title": "Fix Binary Heap Parent/Child Indexing Bug",
    "category": "Bug Fixing & Refactoring",
    "language": "python",
    "prompt": "Fix the off-by-one errors in this 0-indexed binary min-heap implementation. Provide a corrected `MinHeap` class with `parent_index(i: int) -> int`, `left_child_index(i: int) -> int`, and `right_child_index(i: int) -> int`.",
    "signature": "class MinHeap:",
    "test_cases": [
      {
        "script": "h = MinHeap()\nassert h.parent_index(1) == 0\nassert h.parent_index(2) == 0\nassert h.parent_index(3) == 1\nassert h.left_child_index(0) == 1\nassert h.right_child_index(0) == 2\nassert h.left_child_index(1) == 3\nassert h.right_child_index(1) == 4"
      }
    ],
    "reference_solution": "class MinHeap:\n    @staticmethod\n    def parent_index(i: int) -> int:\n        return (i - 1) // 2\n\n    @staticmethod\n    def left_child_index(i: int) -> int:\n        return 2 * i + 1\n\n    @staticmethod\n    def right_child_index(i: int) -> int:\n        return 2 * i + 2"
  },
  {
    "id": "task_17",
    "title": "SQL Parameterized Query Sanitizer",
    "category": "Bug Fixing & Refactoring",
    "language": "python",
    "prompt": "Write a Python function `build_safe_query(table: str, filters: dict, allowed_tables: list[str]) -> tuple[str, tuple]` that safely constructs a parameterized SQL SELECT query. Validates that `table` is in `allowed_tables` (raising ValueError if not) and converts `filters` into 'WHERE key = %s' clauses with parameters tuple. Return `(query_sql, params_tuple)`.",
    "signature": "def build_safe_query(table: str, filters: dict, allowed_tables: list[str]) -> tuple[str, tuple]:",
    "test_cases": [
      {
        "input": [
          "models",
          {
            "context_window": 262144,
            "status": "active"
          },
          [
            "models",
            "benchmarks"
          ]
        ],
        "expected": [
          "SELECT * FROM models WHERE context_window = %s AND status = %s",
          [
            262144,
            "active"
          ]
        ]
      }
    ],
    "reference_solution": "def build_safe_query(table: str, filters: dict, allowed_tables: list[str]) -> tuple:\n    if table not in allowed_tables:\n        raise ValueError(f'Invalid table name: {table}')\n    if not filters:\n        return f'SELECT * FROM {table}', ()\n    clauses = [f'{k} = %s' for k in filters.keys()]\n    query = f'SELECT * FROM {table} WHERE ' + ' AND '.join(clauses)\n    return query, tuple(filters.values())"
  },
  {
    "id": "task_18",
    "title": "Circular Reference Detector in Object Graph",
    "category": "Bug Fixing & Refactoring",
    "language": "python",
    "prompt": "Write a Python function `has_cycle(graph: dict[str, list[str]]) -> bool` that detects if a directed graph contains a cycle.",
    "signature": "def has_cycle(graph: dict[str, list[str]]) -> bool:",
    "test_cases": [
      {
        "input": [
          {
            "A": [
              "B"
            ],
            "B": [
              "C"
            ],
            "C": [
              "A"
            ]
          }
        ],
        "expected": true
      },
      {
        "input": [
          {
            "A": [
              "B",
              "C"
            ],
            "B": [
              "D"
            ],
            "C": [
              "D"
            ],
            "D": [

            ]
          }
        ],
        "expected": false
      }
    ],
    "reference_solution": "def has_cycle(graph: dict) -> bool:\n    visited = {}\n    def dfs(node):\n        visited[node] = 1\n        for neighbor in graph.get(node, []):\n            if visited.get(neighbor) == 1:\n                return True\n            if visited.get(neighbor) != 2:\n                if dfs(neighbor): return True\n        visited[node] = 2\n        return False\n    for node in graph:\n        if node not in visited:\n            if dfs(node): return True\n    return False"
  },
  {
    "id": "task_19",
    "title": "Flatten Nested Array to Target Depth",
    "category": "Bug Fixing & Refactoring",
    "language": "python",
    "prompt": "Write a Python function `flatten_list(nested: list, depth: int = 1) -> list` that flattens an array up to the specified `depth`. If depth is negative or 0, return the list as-is.",
    "signature": "def flatten_list(nested: list, depth: int = 1) -> list:",
    "test_cases": [
      {
        "input": [
          [
            1,
            [
              2,
              [
                3,
                [
                  4
                ]
              ],
              5
            ]
          ],
          1
        ],
        "expected": [
          1,
          2,
          [
            3,
            [
              4
            ]
          ],
          5
        ]
      },
      {
        "input": [
          [
            1,
            [
              2,
              [
                3,
                [
                  4
                ]
              ],
              5
            ]
          ],
          2
        ],
        "expected": [
          1,
          2,
          3,
          [
            4
          ],
          5
        ]
      },
      {
        "input": [
          [
            1,
            [
              2,
              3
            ]
          ],
          0
        ],
        "expected": [
          1,
          [
            2,
            3
          ]
        ]
      }
    ],
    "reference_solution": "def flatten_list(nested: list, depth: int = 1) -> list:\n    if depth <= 0:\n        return nested\n    res = []\n    for item in nested:\n        if isinstance(item, list):\n            res.extend(flatten_list(item, depth - 1))\n        else:\n            res.append(item)\n    return res"
  },
  {
    "id": "task_20",
    "title": "ISO 8601 Duration Parser to Seconds",
    "category": "Bug Fixing & Refactoring",
    "language": "python",
    "prompt": "Write a Python function `iso_duration_to_seconds(duration_str: str) -> int` that parses an ISO 8601 duration (e.g. 'P1DT2H3M4S', 'PT15M', 'PT1H30S') into total seconds. Assume 1 day = 86400 seconds.",
    "signature": "def iso_duration_to_seconds(duration_str: str) -> int:",
    "test_cases": [
      {
        "input": [
          "PT1H30M"
        ],
        "expected": 5400
      },
      {
        "input": [
          "P1DT2H"
        ],
        "expected": 93600
      },
      {
        "input": [
          "PT45S"
        ],
        "expected": 45
      }
    ],
    "reference_solution": "import re\n\ndef iso_duration_to_seconds(duration: str) -> int:\n    m = re.match(r'^P(?:(\\d+)D)?(?:T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?)?$', duration)\n    if not m: return 0\n    days, hours, mins, secs = [int(x) if x else 0 for x in m.groups()]\n    return days * 86400 + hours * 3600 + mins * 60 + secs"
  },
  {
    "id": "task_21",
    "title": "Python Retry with Exponential Backoff Decorator",
    "category": "Polyglot & Scripting",
    "language": "python",
    "prompt": "Write a Python decorator `retry(max_retries: int = 3, exceptions: tuple = (Exception,))` that retries the wrapped function upon catching any of the specified exceptions up to `max_retries` times before re-raising.",
    "signature": "def retry(max_retries: int = 3, exceptions: tuple = (Exception,)):",
    "test_cases": [
      {
        "script": "calls = [0]\n@retry(max_retries=3, exceptions=(ValueError,))\ndef flaky():\n    calls[0] += 1\n    if calls[0] < 3: raise ValueError('Fail')\n    return 'Success'\nassert flaky() == 'Success'\nassert calls[0] == 3"
      }
    ],
    "reference_solution": "import functools\n\ndef retry(max_retries: int = 3, exceptions: tuple = (Exception,)):\n    def decorator(fn):\n        @functools.wraps(fn)\n        def wrapper(*args, **kwargs):\n            attempts = 0\n            while True:\n                try:\n                    return fn(*args, **kwargs)\n                except exceptions as e:\n                    attempts += 1\n                    if attempts >= max_retries:\n                        raise e\n        return wrapper\n    return decorator"
  },
  {
    "id": "task_22",
    "title": "Promise.allSettled Polyfill Logic",
    "category": "Polyglot & Scripting",
    "language": "javascript",
    "prompt": "Write a JavaScript function `allSettledPolyfill(promises)` that returns a Promise resolving to an array of outcome objects `{status: 'fulfilled', value: ...}` or `{status: 'rejected', reason: ...}` once all input promises settle.",
    "signature": "function allSettledPolyfill(promises)",
    "test_cases": [
      {
        "description": "Settles mixed resolved and rejected promises",
        "expected_status": [
          "fulfilled",
          "rejected"
        ]
      }
    ],
    "reference_solution": "function allSettledPolyfill(promises) {\n  return Promise.all(\n    promises.map(p =>\n      Promise.resolve(p).then(\n        value => ({ status: 'fulfilled', value }),\n        reason => ({ status: 'rejected', reason })\n      )\n    )\n  );\n}"
  },
  {
    "id": "task_23",
    "title": "Top N Earners per Department SQL Query",
    "category": "Polyglot & Scripting",
    "language": "sql",
    "prompt": "Write a standard SQL query using window functions (`DENSE_RANK()`) to find the employees who earn the top 3 unique salaries in each department. Schema: `Employee(id, name, salary, department_id)`, `Department(id, name)`.",
    "signature": "SELECT Department, Employee, Salary FROM ...",
    "test_cases": [
      {
        "keyword": "DENSE_RANK() OVER"
      }
    ],
    "reference_solution": "WITH RankedSalaries AS (\n    SELECT \n        d.name AS Department,\n        e.name AS Employee,\n        e.salary AS Salary,\n        DENSE_RANK() OVER (PARTITION BY e.department_id ORDER BY e.salary DESC) AS rnk\n    FROM Employee e\n    JOIN Department d ON e.department_id = d.id\n)\nSELECT Department, Employee, Salary\nFROM RankedSalaries\nWHERE rnk <= 3;"
  },
  {
    "id": "task_24",
    "title": "Matrix Spiral Order Traversal",
    "category": "Polyglot & Scripting",
    "language": "python",
    "prompt": "Write a Python function `spiral_order(matrix: list[list[int]]) -> list[int]` that returns all elements of the matrix in spiral order (clockwise from top-left).",
    "signature": "def spiral_order(matrix: list[list[int]]) -> list[int]:",
    "test_cases": [
      {
        "input": [
          [
            [
              1,
              2,
              3
            ],
            [
              4,
              5,
              6
            ],
            [
              7,
              8,
              9
            ]
          ]
        ],
        "expected": [
          1,
          2,
          3,
          6,
          9,
          8,
          7,
          4,
          5
        ]
      },
      {
        "input": [
          [
            [
              1,
              2,
              3,
              4
            ],
            [
              5,
              6,
              7,
              8
            ],
            [
              9,
              10,
              11,
              12
            ]
          ]
        ],
        "expected": [
          1,
          2,
          3,
          4,
          8,
          12,
          11,
          10,
          9,
          5,
          6,
          7
        ]
      }
    ],
    "reference_solution": "def spiral_order(matrix: list[list[int]]) -> list[int]:\n    if not matrix: return []\n    res = []\n    top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1\n    while top <= bottom and left <= right:\n        for j in range(left, right + 1):\n            res.append(matrix[top][j])\n        top += 1\n        for i in range(top, bottom + 1):\n            res.append(matrix[i][right])\n        right -= 1\n        if top <= bottom:\n            for j in range(right, left - 1, -1):\n                res.append(matrix[bottom][j])\n            bottom -= 1\n        if left <= right:\n            for i in range(bottom, top - 1, -1):\n                res.append(matrix[i][left])\n            left += 1\n    return res"
  },
  {
    "id": "task_25",
    "title": "Consistent Hashing Ring Node Lookup",
    "category": "Polyglot & Scripting",
    "language": "python",
    "prompt": "Implement a `ConsistentHashRing` with `__init__(self, replicas: int = 3)`, `add_node(self, node: str)`, and `get_node(self, key: str) -> str`. Use md5 integer hashing. Keys are assigned to the nearest node clockwise along the ring.",
    "signature": "class ConsistentHashRing:",
    "test_cases": [
      {
        "script": "ring = ConsistentHashRing(replicas=3)\nring.add_node('node-1')\nring.add_node('node-2')\nring.add_node('node-3')\nn1 = ring.get_node('user_1001')\nn2 = ring.get_node('user_2002')\nassert n1 in ['node-1', 'node-2', 'node-3']\nassert n2 in ['node-1', 'node-2', 'node-3']"
      }
    ],
    "reference_solution": "import hashlib, bisect\n\nclass ConsistentHashRing:\n    def __init__(self, replicas: int = 3):\n        self.replicas = replicas\n        self.ring = []\n        self.ring_map = {}\n\n    def _hash(self, val: str) -> int:\n        return int(hashlib.md5(val.encode('utf-8')).hexdigest(), 16)\n\n    def add_node(self, node: str):\n        for i in range(self.replicas):\n            h = self._hash(f'{node}:{i}')\n            bisect.insort(self.ring, h)\n            self.ring_map[h] = node\n\n    def get_node(self, key: str) -> str:\n        if not self.ring:\n            return None\n        h = self._hash(key)\n        idx = bisect.bisect_right(self.ring, h)\n        if idx == len(self.ring):\n            idx = 0\n        return self.ring_map[self.ring[idx]]"
  }
]