{"id": "codehard-test-000000", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-18)\nobj.median() # -18\nobj.median() # -18\nobj.add(4)\nobj.add(-13)\nobj.median() # -13\nobj.add(2)\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000001", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `StreamMedian()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahden keskimmäisen arvon keskiarvo (liukuluku, esim. 2.5). Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nEsimerkki:\n```python\nobj = StreamMedian()\nobj.add(-20)\nobj.median() # -20\nobj.add(-14)\nobj.add(-15)\nobj.add(16)\nobj.median() # -14.5\nobj.add(12)\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "\n- Vain keskikohta merkitsee, joten pidä puoliskot erillään järjestetyn listan sijaan.\n- Lisää alempaan puoliskoon, siirrä sen suurin ylempään ja tasapainota niin, että alemmassa on ylimääräinen.\n- Pythonin heapq on minimikeko: tallenna maksimikekoon negatiiviset arvot.\n- Reunatapaukset: yksi luku, toistot, negatiiviset luvut, parillinen ja pariton määrä.\n- Vaativuus: O(log n) per add, O(1) per median, O(n) muistia.\n\n\nKaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia.\n\nTestit:\n```python\nobj = StreamMedian()\nobj.add(-3)\nobj.add(20)\nassert obj.median() == 8.5\nassert obj.median() == 8.5\nobj.add(9)\nassert obj.median() == 9\nassert obj.median() == 9\nassert obj.median() == 9\nobj.add(-5)\nobj.add(13)\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000002", "messages": [{"role": "user", "content": "**Sadeveden kertyminen**\n\n`heights[i]` on 1 leveän seinäosan korkeus. Sateen jälkeen vettä kertyy korkeampien osien väliin. Palauta kertyneen veden kokonaismäärä. Osia voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> rain_water([0, 0, 3, 1])\n0\n>>> rain_water([0, 2, 2, 3, 6, 2, 5, 4, 6])\n7\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "\n- Vesi kohdassa i = min(maksimi vasemmalla, maksimi oikealla) - heights[i], ei koskaan negatiivinen.\n- Molempien maksimien laskeminen joka i:lle on O(n²).\n- Juoksevat maksimit (tai kaksi osoitinta) antavat jokaisen tason lineaarisessa ajassa.\n- Reunatapaukset: tyhjä lista, alle 3 seinää, tasainen tai monotoninen profiili.\n- Vaativuus: O(n) aikaa, O(1) lisämuistia.\n\n\nKaksi osoitinta molemmista päistä: matalampi puoli määrää vedenpinnan, joten siirrä sitä sisään ja pidä kirjaa sen puolen korkeimmasta seinästä.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia.\n\nTestit:\n```python\nassert rain_water([0, 0, 3, 1]) == 0\nassert rain_water([0, 2, 2, 3, 6, 2, 5, 4, 6]) == 7\nassert rain_water([3, 0, 3]) == 3\nassert rain_water([4, 2, 0, 3, 2, 5]) == 9\nassert rain_water([]) == 0\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.water.trap0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000003", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('10126126266')\n18\n>>> decode_ways('12122111')\n34\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000004", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('2120212122')\n26\n>>> count_decodings('26')\n2\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000005", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-5)\nobj.add(-1)\nobj.median() # -5\nobj.add(-19)\nobj.add(-15)\nobj.median() # -15\nobj.median() # -15\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = MedianTracker()\nobj.add(0)\nassert obj.median() == 0\nobj.add(12)\nobj.add(12)\nobj.add(11)\nobj.add(0)\nassert obj.median() == 11\n\nobj = MedianTracker()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000006", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(7, [[2, 1], [2, 3]])\nTrue\n>>> is_bipartite(6, [[4, 0], [4, 1], [2, 1], [1, 5]])\nTrue\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000007", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> most_water([3, 6, 4, 5, 2, 6])\n24\n>>> most_water([4, 1])\n1\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Two pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000008", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('1126622621')\n30\n>>> decode_ways('021611222')\n0\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000009", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> count_decodings('66112061')\n2\n>>> count_decodings('20211202')\n3\n```\n\nToteuta se Pythonilla."}, {"role": "assistant", "content": "Dynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000010", "messages": [{"role": "user", "content": "**Days until a warmer day**\n\n`temps[i]` is the temperature on day `i`. For each day, return how many days you have to wait for a strictly warmer day, or 0 if no warmer day comes. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> steps_to_greater([2, 2, 1, 2, 5, 0])\n[4, 3, 1, 1, 0, 0]\n>>> steps_to_greater([9, 0, 4, 4, 7, 0, 4, 8, 8])\n[0, 1, 2, 1, 3, 1, 1, 0, 0]\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "steps_to_greater", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000011", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater_circular([6, 9, 2, 0, 7])\n[9, -1, 7, 7, 9]\n>>> next_greater_circular([])\n[]\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000012", "messages": [{"role": "user", "content": "**Sadeveden kertyminen**\n\n`heights[i]` on 1 leveän seinäosan korkeus. Sateen jälkeen vettä kertyy korkeampien osien väliin. Palauta kertyneen veden kokonaismäärä. Osia voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> rain_water([4, 0, 3, 1, 0, 4, 3, 2, 2, 0])\n12\n>>> rain_water([])\n0\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "Kaksi osoitinta molemmista päistä: matalampi puoli määrää vedenpinnan, joten siirrä sitä sisään ja pidä kirjaa sen puolen korkeimmasta seinästä.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\nMiksi tämä toimii:\n- Molempien maksimien laskeminen joka i:lle on O(n²).\n- Juoksevat maksimit (tai kaksi osoitinta) antavat jokaisen tason lineaarisessa ajassa.\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia."}], "meta": {"kind": "code.hard.water.trap0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000013", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> count_decodings('1221101102')\n5\n>>> count_decodings('202022')\n2\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(1) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nMiksi tämä toimii:\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n\n**Vaativuus:** O(n) aikaa, O(1) muistia."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000014", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('201')\n1\n>>> count_decodings('22010226')\n3\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000015", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater([7, 2])\n[-1, -1]\n>>> next_greater([5, 4, 3, 5, 1, 0, 6, 4, 3, 1])\n[6, 5, 5, 6, 6, 6, -1, -1, -1, -1]\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert next_greater([7, 2]) == [-1, -1]\nassert next_greater([5, 4, 3, 5, 1, 0, 6, 4, 3, 1]) == [6, 5, 5, 6, 6, 6, -1, -1, -1, -1]\nassert next_greater([7]) == [-1]\nassert next_greater([2, 1, 2, 4, 3]) == [4, 2, 4, -1, -1]\nassert next_greater([]) == []\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000016", "messages": [{"role": "user", "content": "**Sadeveden kertyminen**\n\n`heights[i]` on 1 leveän seinäosan korkeus. Sateen jälkeen vettä kertyy korkeampien osien väliin. Palauta kertyneen veden kokonaismäärä. Osia voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> rain_water([5, 3, 5, 6, 5, 0, 0, 4, 3])\n10\n>>> rain_water([1, 0, 4, 0, 1, 0, 2, 4])\n14\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "\n- Vesi kohdassa i = min(maksimi vasemmalla, maksimi oikealla) - heights[i], ei koskaan negatiivinen.\n- Molempien maksimien laskeminen joka i:lle on O(n²).\n- Juoksevat maksimit (tai kaksi osoitinta) antavat jokaisen tason lineaarisessa ajassa.\n- Reunatapaukset: tyhjä lista, alle 3 seinää, tasainen tai monotoninen profiili.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nRuudun yllä oleva vesi on min(korkein seinä vasemmalla, korkein seinä oikealla) miinus sen korkeus; laske molemmat juoksevat maksimit etukäteen.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.water.trap1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000017", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> trapped_water([4])\n0\n>>> trapped_water([2, 5, 4, 0, 4, 4, 2])\n4\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(n) space.\n\n\nThe water above a cell is min(highest wall to its left, highest wall to its right) minus its height; precompute both running maxima.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\nWhy it works:\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.water.trap1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000018", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(5, [[0, 0], [1, 1], [2, 0], [0, 0], [0, 0], [2, 0], [3, 3]])\nFalse\n>>> can_split_in_two(7, [[4, 0], [5, 6], [6, 2]])\nTrue\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000019", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-13)\nobj.median() # -13\nobj.add(-12)\nobj.median() # -12.5\nobj.add(-8)\nobj.median() # -12\nobj.add(-12)\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\nWhy it works:\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000020", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('0216021')\n0\n>>> decode_ways('1012')\n2\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(n) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000021", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-12)\nobj.median() # -12\nobj.median() # -12\nobj.median() # -12\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000022", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-3)\nobj.add(-4)\nobj.add(5)\nobj.median() # -3\nobj.add(13)\nobj.add(14)\nobj.median() # 5\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000023", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `StreamMedian()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahdesta keskimmäisestä arvosta pienempi. Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nEsimerkki:\n```python\nobj = StreamMedian()\nobj.add(-17)\nobj.add(7)\nobj.median() # -17\nobj.add(-4)\nobj.median() # -4\nobj.add(-4)\nobj.median() # -4\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "Kaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia.\n\nTestit:\n```python\nobj = StreamMedian()\nobj.add(19)\nobj.add(17)\nobj.add(8)\nobj.add(15)\nassert obj.median() == 15\nobj.add(-10)\nassert obj.median() == 15\nassert obj.median() == 15\nobj.add(-10)\nobj.add(17)\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.running_median.low", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000024", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `MedianTracker()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahden keskimmäisen arvon keskiarvo (liukuluku, esim. 2.5). Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nEsimerkki:\n```python\nobj = MedianTracker()\nobj.add(10)\nobj.add(-19)\nobj.add(-19)\nobj.add(3)\nobj.median() # -8.0\nobj.median() # -8.0\nobj.add(-16)\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "\n- Vain keskikohta merkitsee, joten pidä puoliskot erillään järjestetyn listan sijaan.\n- Lisää alempaan puoliskoon, siirrä sen suurin ylempään ja tasapainota niin, että alemmassa on ylimääräinen.\n- Pythonin heapq on minimikeko: tallenna maksimikekoon negatiiviset arvot.\n- Reunatapaukset: yksi luku, toistot, negatiiviset luvut, parillinen ja pariton määrä.\n- Vaativuus: O(log n) per add, O(1) per median, O(n) muistia.\n\n\nKaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000025", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater([3])\n[-1]\n>>> next_greater([0, 5, 6, 9, 5, 3, 0, 1, 8, 6])\n[5, 6, 9, -1, 8, 8, 1, 8, -1, -1]\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000026", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('0212622201')\n0\n>>> decode_ways('162026')\n4\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space.\n\nTests:\n```python\nassert decode_ways('0212622201') == 0\nassert decode_ways('162026') == 4\nassert decode_ways('1111111111') == 89\nassert decode_ways('0') == 0\nassert decode_ways('100') == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000027", "messages": [{"role": "user", "content": "**Eniten vettä vetävä astia**\n\n`heights[i]` on pystyviivan korkeus kohdassa x = i. Valitse kaksi viivaa, jotka x-akselin kanssa vetävät eniten vettä, ja palauta se määrä (lyhyempi viiva kertaa etäisyys). Viivoja voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> most_water([6])\n0\n>>> most_water([5, 5, 3, 4, 0, 4, 5])\n30\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "Kaksi osoitinta molemmista päistä; siirrä aina lyhyempää viivaa sisäänpäin, koska sen säilyttäminen voi antaa vain pienempiä astioita.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia."}], "meta": {"kind": "code.hard.water.container0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000028", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(3)\nobj.add(2)\nobj.add(18)\nobj.add(-5)\nobj.add(13)\nobj.add(11)\nobj.median() # 3\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000029", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(4, [[1, 0], [1, 1]])\nFalse\n>>> is_bipartite(4, [[2, 0], [3, 1], [3, 1], [2, 1], [3, 1], [1, 0]])\nFalse\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000030", "messages": [{"role": "user", "content": "**Päiviä lämpimämpään päivään**\n\n`temps[i]` on päivän `i` lämpötila. Palauta jokaiselle päivälle, montako päivää pitää odottaa aidosti lämpimämpää päivää, tai 0, jos sellaista ei tule. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> days_until_warmer([])\n[]\n>>> days_until_warmer([4, 5, 4, 8, 2, 4])\n[1, 2, 1, 0, 1, 0]\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\nMiksi tämä toimii:\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "days_until_warmer", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000031", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(8, [])\nTrue\n>>> can_split_in_two(4, [[0, 2], [1, 3], [0, 1], [0, 3], [1, 1], [0, 1]])\nFalse\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000032", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-15)\nobj.median() # -15\nobj.add(3)\nobj.median() # -6.0\nobj.add(14)\nobj.add(-8)\nobj.median() # -2.5\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(19)\nassert obj.median() == 19\nobj.add(-6)\nassert obj.median() == 6.5\nassert obj.median() == 6.5\nobj.add(9)\nobj.add(3)\nobj.add(-14)\nassert obj.median() == 3\nobj.add(-13)\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000033", "messages": [{"role": "user", "content": "**Eniten vettä vetävä astia**\n\n`heights[i]` on pystyviivan korkeus kohdassa x = i. Valitse kaksi viivaa, jotka x-akselin kanssa vetävät eniten vettä, ja palauta se määrä (lyhyempi viiva kertaa etäisyys). Viivoja voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> max_container([2])\n0\n>>> max_container([6, 2, 5, 5, 2, 6, 2])\n30\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "\n- Kaikkien parien tarkistaminen on O(n²).\n- Kun lyhyempi viiva on kiinnitetty, jokainen kapeampi astia on huonompi, joten pudota se viiva.\n- Jokainen askel poistaa yhden viivan: lineaarinen aika.\n- Reunatapaukset: alle 2 viivaa, yhtä korkeat viivat, nollat.\n- Vaativuus: O(n) aikaa, O(1) lisämuistia.\n\n\nKaksi osoitinta molemmista päistä; siirrä aina lyhyempää viivaa sisäänpäin, koska sen säilyttäminen voi antaa vain pienempiä astioita.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\nMiksi tämä toimii:\n- Kun lyhyempi viiva on kiinnitetty, jokainen kapeampi astia on huonompi, joten pudota se viiva.\n- Jokainen askel poistaa yhden viivan: lineaarinen aika.\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia."}], "meta": {"kind": "code.hard.water.container0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000034", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('20')\n1\n>>> decode_ways('22211006611')\n0\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000035", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> decode_ways('0102')\n0\n>>> decode_ways('220')\n1\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(1) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Vaativuus:** O(n) aikaa, O(1) muistia.\n\nTestit:\n```python\nassert decode_ways('0102') == 0\nassert decode_ways('220') == 1\nassert decode_ways('100') == 0\nassert decode_ways('0') == 0\nassert decode_ways('27') == 1\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000036", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> max_container([6, 3, 5, 4, 3, 4, 6, 4])\n36\n>>> max_container([])\n0\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "Two pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000037", "messages": [{"role": "user", "content": "**Päiviä lämpimämpään päivään**\n\n`temps[i]` on päivän `i` lämpötila. Palauta jokaiselle päivälle, montako päivää pitää odottaa aidosti lämpimämpää päivää, tai 0, jos sellaista ei tule. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> steps_to_greater([9, 2, 4])\n[0, 1, 0]\n>>> steps_to_greater([0, 6, 0, 1, 4, 7, 2, 3, 9, 8])\n[1, 4, 1, 1, 1, 3, 1, 1, 0, 0]\n```\n\nToteuta se Pythonilla."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "steps_to_greater", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000038", "messages": [{"role": "user", "content": "**Seuraava suurempi alkio kehällä**\n\n`nums` on kehämäinen: viimeisen alkion jälkeen tulee taas ensimmäinen. Palauta jokaiselle alkiolle ensimmäinen aidosti suurempi arvo eteenpäin kulkien (kehän ympäri), tai -1, jos sellaista ei ole. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> next_greater_circular([3, 0, 1, 6, 0, 9])\n[6, 1, 6, 9, 9, -1]\n>>> next_greater_circular([])\n[]\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle. Kaksi kierrosta taulukon yli hoitaa kehän.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000039", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> max_container([3, 6, 4, 5])\n10\n>>> max_container([1, 2, 5, 1, 1, 3, 0])\n9\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- Checking all pairs is O(n²).\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n- Edge cases: fewer than 2 lines, equal heights, zeros.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\nWhy it works:\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000040", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-8)\nobj.add(14)\nobj.median() # 3.0\nobj.add(17)\nobj.add(-8)\nobj.median() # 3.0\nobj.median() # 3.0\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000041", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> trapped_water([6, 3])\n0\n>>> trapped_water([4, 2, 2, 3, 6, 0, 6, 3, 1])\n11\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\n**Complexity:** O(n) time, O(1) extra space.\n\nTests:\n```python\nassert trapped_water([6, 3]) == 0\nassert trapped_water([4, 2, 2, 3, 6, 0, 6, 3, 1]) == 11\nassert trapped_water([3, 0, 3]) == 3\nassert trapped_water([2, 0]) == 0\nassert trapped_water([3]) == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000042", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-4)\nobj.add(-18)\nobj.median() # -18\nobj.median() # -18\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\nWhy it works:\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000043", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `MedianTracker()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahdesta keskimmäisestä arvosta pienempi. Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nEsimerkki:\n```python\nobj = MedianTracker()\nobj.add(-6)\nobj.median() # -6\nobj.add(16)\nobj.median() # -6\nobj.add(3)\nobj.add(-2)\nobj.add(19)\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "\n- Vain keskikohta merkitsee, joten pidä puoliskot erillään järjestetyn listan sijaan.\n- Lisää alempaan puoliskoon, siirrä sen suurin ylempään ja tasapainota niin, että alemmassa on ylimääräinen.\n- Pythonin heapq on minimikeko: tallenna maksimikekoon negatiiviset arvot.\n- Reunatapaukset: yksi luku, toistot, negatiiviset luvut, parillinen ja pariton määrä.\n- Vaativuus: O(log n) per add, O(1) per median, O(n) muistia.\n\n\nKaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\nMiksi tämä toimii:\n- Lisää alempaan puoliskoon, siirrä sen suurin ylempään ja tasapainota niin, että alemmassa on ylimääräinen.\n- Pythonin heapq on minimikeko: tallenna maksimikekoon negatiiviset arvot.\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia."}], "meta": {"kind": "code.hard.running_median.low", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000044", "messages": [{"role": "user", "content": "**Sadeveden kertyminen**\n\n`heights[i]` on 1 leveän seinäosan korkeus. Sateen jälkeen vettä kertyy korkeampien osien väliin. Palauta kertyneen veden kokonaismäärä. Osia voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> trapped_water([6, 3, 3, 5, 3, 6, 1])\n10\n>>> trapped_water([3])\n0\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "Ruudun yllä oleva vesi on min(korkein seinä vasemmalla, korkein seinä oikealla) miinus sen korkeus; laske molemmat juoksevat maksimit etukäteen.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia.\n\nTestit:\n```python\nassert trapped_water([6, 3, 3, 5, 3, 6, 1]) == 10\nassert trapped_water([3]) == 0\nassert trapped_water([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) == 6\nassert trapped_water([2, 0]) == 0\nassert trapped_water([4, 2, 0, 3, 2, 5]) == 9\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.water.trap1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000045", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('1110620201')\n2\n>>> decode_ways('')\n1\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000046", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_larger_values([4, 1, 9])\n[9, 9, -1]\n>>> next_larger_values([7, 1])\n[-1, -1]\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert next_larger_values([4, 1, 9]) == [9, 9, -1]\nassert next_larger_values([7, 1]) == [-1, -1]\nassert next_larger_values([2, 1, 2, 4, 3]) == [4, 2, 4, -1, -1]\nassert next_larger_values([3, 3, 3]) == [-1, -1, -1]\nassert next_larger_values([1, 2, 3, 4]) == [2, 3, 4, -1]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_larger_values", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000047", "messages": [{"role": "user", "content": "**Eniten vettä vetävä astia**\n\n`heights[i]` on pystyviivan korkeus kohdassa x = i. Valitse kaksi viivaa, jotka x-akselin kanssa vetävät eniten vettä, ja palauta se määrä (lyhyempi viiva kertaa etäisyys). Viivoja voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> max_container([6, 4, 4, 3])\n9\n>>> max_container([1, 6, 1, 6, 4, 5, 0, 6])\n36\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "Kaksi osoitinta molemmista päistä; siirrä aina lyhyempää viivaa sisäänpäin, koska sen säilyttäminen voi antaa vain pienempiä astioita.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia.\n\nTestit:\n```python\nassert max_container([6, 4, 4, 3]) == 9\nassert max_container([1, 6, 1, 6, 4, 5, 0, 6]) == 36\nassert max_container([1, 1]) == 1\nassert max_container([1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49\nassert max_container([5]) == 0\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.water.container0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000048", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(2, [[1, 1], [1, 0], [1, 0], [1, 0], [0, 1], [1, 0], [1, 0]])\nFalse\n>>> can_split_in_two(2, [[1, 1]])\nFalse\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\nWhy it works:\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000049", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(20)\nobj.add(7)\nobj.median() # 7\nobj.add(-18)\nobj.add(10)\nobj.add(1)\nobj.median() # 7\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(-19)\nassert obj.median() == -19\nobj.add(-18)\nassert obj.median() == -19\nobj.add(17)\nassert obj.median() == -18\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000050", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater_circular([9, 3, 9, 9, 9, 6])\n[-1, 9, -1, -1, -1, 9]\n>>> next_greater_circular([0, 0, 3, 2, 0, 2])\n[3, 3, -1, 3, 2, 3]\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000051", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> decode_ways('2122122')\n21\n>>> decode_ways('621226')\n8\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(1) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Vaativuus:** O(n) aikaa, O(1) muistia.\n\nTestit:\n```python\nassert decode_ways('2122122') == 21\nassert decode_ways('621226') == 8\nassert decode_ways('226') == 3\nassert decode_ways('0') == 0\nassert decode_ways('10') == 1\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000052", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> max_container([5, 6])\n5\n>>> max_container([5, 3, 3, 5, 6])\n20\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- Checking all pairs is O(n²).\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n- Edge cases: fewer than 2 lines, equal heights, zeros.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\nWhy it works:\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000053", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('260016')\n0\n>>> decode_ways('2221012')\n6\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000054", "messages": [{"role": "user", "content": "**Days until a warmer day**\n\n`temps[i]` is the temperature on day `i`. For each day, return how many days you have to wait for a strictly warmer day, or 0 if no warmer day comes. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> steps_to_greater([7, 0, 5, 6, 1, 0, 0, 3])\n[0, 1, 1, 0, 3, 2, 1, 0]\n>>> steps_to_greater([3])\n[0]\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\nWhy it works:\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "steps_to_greater", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000055", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> trapped_water([1, 4, 6])\n0\n>>> trapped_water([])\n0\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "Two pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000056", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('22201211')\n10\n>>> count_decodings('')\n1\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(n) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000057", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(8, [])\nTrue\n>>> is_bipartite(5, [[2, 0], [4, 2], [4, 3], [0, 3], [2, 2], [0, 0], [2, 0]])\nFalse\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "Two-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space.\n\nTests:\n```python\nassert is_bipartite(8, [])\nassert not is_bipartite(5, [[2, 0], [4, 2], [4, 3], [0, 3], [2, 2], [0, 0], [2, 0]])\nassert is_bipartite(0, [])\nassert is_bipartite(1, [])\nassert is_bipartite(5, [[0, 1], [2, 3]])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000058", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('0260126112')\n0\n>>> count_decodings('221226211')\n39\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000059", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> count_decodings('26')\n2\n>>> count_decodings('0121')\n0\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\nMiksi tämä toimii:\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000060", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-7)\nobj.median() # -7\nobj.add(-7)\nobj.median() # -7\nobj.add(6)\nobj.median() # -7\nobj.median() # -7\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\nWhy it works:\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000061", "messages": [{"role": "user", "content": "**Seuraava suurempi alkio**\n\nPalauta jokaiselle listan `nums` alkiolle ensimmäinen sen oikealla puolella oleva aidosti suurempi arvo, tai -1, jos sellaista ei ole. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> next_larger_values([4, 1, 6, 8, 9, 8, 6, 1, 0, 2])\n[6, 6, 8, 9, -1, -1, -1, 2, 2, -1]\n>>> next_larger_values([1, 4, 7, 1, 8, 4, 1])\n[4, 7, 8, 8, -1, -1, -1]\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia.\n\nTestit:\n```python\nassert next_larger_values([4, 1, 6, 8, 9, 8, 6, 1, 0, 2]) == [6, 6, 8, 9, -1, -1, -1, 2, 2, -1]\nassert next_larger_values([1, 4, 7, 1, 8, 4, 1]) == [4, 7, 8, 8, -1, -1, -1]\nassert next_larger_values([1, 2, 3, 4]) == [2, 3, 4, -1]\nassert next_larger_values([]) == []\nassert next_larger_values([7]) == [-1]\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_larger_values", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000062", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> most_water([1, 5, 6, 2, 6, 2, 6, 3, 2, 5])\n40\n>>> most_water([0, 3, 2, 1, 3])\n9\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Checking all pairs is O(n²).\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n- Edge cases: fewer than 2 lines, equal heights, zeros.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000063", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(7, [[0, 0], [3, 6], [3, 5], [1, 3], [5, 5], [4, 5]])\nFalse\n>>> can_split_in_two(2, [[0, 0], [0, 1], [0, 0], [0, 1], [1, 0], [0, 1], [0, 0]])\nFalse\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000064", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> can_split_in_two(6, [[3, 0], [3, 2], [1, 5], [3, 4], [4, 0], [4, 0], [5, 2]])\nFalse\n>>> can_split_in_two(4, [[1, 0], [0, 0], [0, 3], [1, 0], [0, 2], [3, 1], [2, 0], [2, 1]])\nFalse\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "Väritä jokainen komponentti kahdella värillä BFS:llä; naapuri, jolla on jo sama väri, todistaa jaon mahdottomaksi.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Vaativuus:** O(n + m) aikaa, O(n + m) muistia.\n\nTestit:\n```python\nassert not can_split_in_two(6, [[3, 0], [3, 2], [1, 5], [3, 4], [4, 0], [4, 0], [5, 2]])\nassert not can_split_in_two(4, [[1, 0], [0, 0], [0, 3], [1, 0], [0, 2], [3, 1], [2, 0], [2, 1]])\nassert can_split_in_two(0, [])\nassert not can_split_in_two(3, [[0, 1], [1, 2], [2, 0]])\nassert can_split_in_two(1, [])\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000065", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('66')\n1\n>>> decode_ways('011')\n0\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space.\n\nTests:\n```python\nassert decode_ways('66') == 1\nassert decode_ways('011') == 0\nassert decode_ways('27') == 1\nassert decode_ways('0') == 0\nassert decode_ways('') == 1\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000066", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> circular_next_larger([9, 9, 5, 0, 4, 7, 5, 0, 4, 0])\n[-1, -1, 7, 4, 7, 9, 9, 4, 9, 9]\n>>> circular_next_larger([0, 9, 6, 1])\n[9, -1, 9, 9]\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert circular_next_larger([9, 9, 5, 0, 4, 7, 5, 0, 4, 0]) == [-1, -1, 7, 4, 7, 9, 9, 4, 9, 9]\nassert circular_next_larger([0, 9, 6, 1]) == [9, -1, 9, 9]\nassert circular_next_larger([3, 3, 3]) == [-1, -1, -1]\nassert circular_next_larger([]) == []\nassert circular_next_larger([4, 3, 2, 1]) == [-1, 4, 4, 4]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "circular_next_larger", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000067", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> decode_ways('60261206611')\n0\n>>> decode_ways('1')\n1\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000068", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> can_split_in_two(1, [[0, 0], [0, 0], [0, 0], [0, 0]])\nFalse\n>>> can_split_in_two(2, [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 1], [1, 1]])\nFalse\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "\n- Verkon voi jakaa kahtia täsmälleen silloin, kun siinä ei ole paritonta sykliä.\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n- Reunatapaukset: ei solmuja, erilliset solmut, silmukka, pariton tai parillinen sykli.\n- Vaativuus: O((n + m) α(n)) aikaa, O(n) muistia.\n\n\nUnion-find solmuille ja niiden vastakkaisille puolille: kaari u-v yhdistää u:n ja ei-v:n sekä v:n ja ei-u:n; jos u ja v päätyvät samaan joukkoon, jako on mahdoton.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Vaativuus:** O((n + m) α(n)) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000069", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(5, [[0, 0], [3, 1], [0, 0], [2, 3], [0, 3], [0, 3], [4, 3], [4, 3]])\nFalse\n>>> can_split_in_two(1, [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]])\nFalse\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O((n + m) α(n)) time, O(n) space.\n\n\nUnion-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space.\n\nTests:\n```python\nassert not can_split_in_two(5, [[0, 0], [3, 1], [0, 0], [2, 3], [0, 3], [0, 3], [4, 3], [4, 3]])\nassert not can_split_in_two(1, [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]])\nassert can_split_in_two(4, [[0, 1], [1, 2], [2, 3], [3, 0]])\nassert can_split_in_two(0, [])\nassert not can_split_in_two(3, [[0, 1], [1, 2], [2, 0]])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000070", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(10)\nobj.add(-3)\nobj.add(5)\nobj.add(0)\nobj.add(10)\nobj.median() # 5\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000071", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> max_container([2, 2, 2, 6, 4, 1, 4, 1, 1, 6])\n36\n>>> max_container([4, 4, 3, 6, 4, 3, 5, 4, 5])\n32\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "Two pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000072", "messages": [{"role": "user", "content": "**Days until a warmer day**\n\n`temps[i]` is the temperature on day `i`. For each day, return how many days you have to wait for a strictly warmer day, or 0 if no warmer day comes. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> days_until_warmer([2, 6, 0, 3, 9, 3])\n[1, 3, 1, 1, 0, 0]\n>>> days_until_warmer([7, 6, 9, 1, 9, 6, 0, 8])\n[2, 1, 0, 1, 0, 2, 1, 0]\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert days_until_warmer([2, 6, 0, 3, 9, 3]) == [1, 3, 1, 1, 0, 0]\nassert days_until_warmer([7, 6, 9, 1, 9, 6, 0, 8]) == [2, 1, 0, 1, 0, 2, 1, 0]\nassert days_until_warmer([7]) == [0]\nassert days_until_warmer([2, 1, 2, 4, 3]) == [3, 1, 1, 0, 0]\nassert days_until_warmer([1, 2, 3, 4]) == [1, 1, 1, 0]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "days_until_warmer", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000073", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(6, [[2, 2], [4, 4]])\nFalse\n>>> can_split_in_two(5, [[3, 2], [2, 4], [2, 3]])\nTrue\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\nWhy it works:\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000074", "messages": [{"role": "user", "content": "**Seuraava suurempi alkio kehällä**\n\n`nums` on kehämäinen: viimeisen alkion jälkeen tulee taas ensimmäinen. Palauta jokaiselle alkiolle ensimmäinen aidosti suurempi arvo eteenpäin kulkien (kehän ympäri), tai -1, jos sellaista ei ole. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> next_greater_circular([])\n[]\n>>> next_greater_circular([8, 3, 1])\n[-1, 8, 8]\n```\n\nToteuta se Pythonilla."}, {"role": "assistant", "content": "\n- Jokaisen myöhemmän alkion tarkistaminen on O(n²); jokainen alkio tarvitsee ratkaista vain kerran.\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n- Reunatapaukset: tyhjä lista, yksi alkio, kaikki yhtä suuria, aidosti laskeva.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nMonotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle. Kaksi kierrosta taulukon yli hoitaa kehän.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000075", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> count_decodings('2026211')\n6\n>>> count_decodings('0')\n0\n```\n\nToteuta se Pythonilla."}, {"role": "assistant", "content": "Dynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000076", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(10)\nobj.add(-11)\nobj.median() # -11\nobj.add(-12)\nobj.median() # -11\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = MedianTracker()\nobj.add(-1)\nobj.add(10)\nobj.add(-15)\nobj.add(9)\nobj.add(-11)\nassert obj.median() == -1\n\nobj = MedianTracker()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000077", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(18)\nobj.median() # 18\nobj.add(19)\nobj.median() # 18.5\nobj.add(-2)\nobj.median() # 18\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = MedianTracker()\nobj.add(-20)\nassert obj.median() == -20\nobj.add(14)\nobj.add(-10)\nassert obj.median() == -10\n\nobj = MedianTracker()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000078", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `StreamMedian()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahdesta keskimmäisestä arvosta pienempi. Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nEsimerkki:\n```python\nobj = StreamMedian()\nobj.add(-2)\nobj.add(8)\nobj.add(-1)\nobj.add(-10)\nobj.add(3)\nobj.add(-19)\nobj.add(-6)\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "\n- Vain keskikohta merkitsee, joten pidä puoliskot erillään järjestetyn listan sijaan.\n- Lisää alempaan puoliskoon, siirrä sen suurin ylempään ja tasapainota niin, että alemmassa on ylimääräinen.\n- Pythonin heapq on minimikeko: tallenna maksimikekoon negatiiviset arvot.\n- Reunatapaukset: yksi luku, toistot, negatiiviset luvut, parillinen ja pariton määrä.\n- Vaativuus: O(log n) per add, O(1) per median, O(n) muistia.\n\n\nKaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia.\n\nTestit:\n```python\nobj = StreamMedian()\nobj.add(-13)\nobj.add(-1)\nassert obj.median() == -13\nassert obj.median() == -13\nassert obj.median() == -13\nassert obj.median() == -13\nobj.add(1)\nassert obj.median() == -1\nobj.add(20)\nobj.add(2)\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.running_median.low", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000079", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> decode_ways('')\n1\n>>> decode_ways('01162')\n0\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(1) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nMiksi tämä toimii:\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n\n**Vaativuus:** O(n) aikaa, O(1) muistia."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000080", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(4, [[0, 3], [3, 2], [2, 1], [2, 2], [3, 0], [3, 2], [1, 2]])\nFalse\n>>> is_bipartite(2, [[1, 1]])\nFalse\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\nWhy it works:\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000081", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(3, [[0, 2], [0, 0], [2, 2], [1, 0], [1, 0], [1, 0], [2, 1], [1, 0]])\nFalse\n>>> can_split_in_two(7, [[0, 1], [1, 1], [2, 3], [3, 6], [4, 5], [6, 1]])\nFalse\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "Two-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000082", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> most_water([4, 4])\n4\n>>> most_water([0, 0, 6, 3, 5])\n10\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- Checking all pairs is O(n²).\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n- Edge cases: fewer than 2 lines, equal heights, zeros.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\nWhy it works:\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000083", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('')\n1\n>>> count_decodings('20662121')\n5\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000084", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('06222222212')\n0\n>>> count_decodings('10120261211')\n10\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(n) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000085", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(5)\nobj.median() # 5\nobj.add(-20)\nobj.median() # -7.5\nobj.median() # -7.5\nobj.add(6)\nobj.add(7)\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\nWhy it works:\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000086", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> is_bipartite(5, [[1, 4], [0, 1], [3, 1], [3, 0]])\nFalse\n>>> is_bipartite(6, [[4, 0], [5, 3], [1, 5], [3, 4]])\nTrue\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "\n- Verkon voi jakaa kahtia täsmälleen silloin, kun siinä ei ole paritonta sykliä.\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n- Reunatapaukset: ei solmuja, erilliset solmut, silmukka, pariton tai parillinen sykli.\n- Vaativuus: O((n + m) α(n)) aikaa, O(n) muistia.\n\n\nUnion-find solmuille ja niiden vastakkaisille puolille: kaari u-v yhdistää u:n ja ei-v:n sekä v:n ja ei-u:n; jos u ja v päätyvät samaan joukkoon, jako on mahdoton.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Vaativuus:** O((n + m) α(n)) aikaa, O(n) muistia.\n\nTestit:\n```python\nassert not is_bipartite(5, [[1, 4], [0, 1], [3, 1], [3, 0]])\nassert is_bipartite(6, [[4, 0], [5, 3], [1, 5], [3, 4]])\nassert not is_bipartite(1, [[0, 0]])\nassert is_bipartite(5, [[0, 1], [2, 3]])\nassert is_bipartite(1, [])\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000087", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(3)\nobj.add(7)\nobj.add(-19)\nobj.median() # 3\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(-12)\nobj.add(17)\nobj.add(-17)\nobj.add(-17)\nassert obj.median() == -14.5\nobj.add(7)\nobj.add(11)\nobj.add(-4)\nassert obj.median() == -4\nassert obj.median() == -4\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000088", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([4, 5, 3, 2, 4, 1, 0, 5, 3])\n15\n>>> rain_water([2])\n0\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "Two pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\n**Complexity:** O(n) time, O(1) extra space.\n\nTests:\n```python\nassert rain_water([4, 5, 3, 2, 4, 1, 0, 5, 3]) == 15\nassert rain_water([2]) == 0\nassert rain_water([2, 0]) == 0\nassert rain_water([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) == 6\nassert rain_water([3, 0, 3]) == 3\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000089", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(6)\nobj.add(-4)\nobj.add(-2)\nobj.median() # -2\nobj.add(15)\nobj.median() # 2.0\nobj.add(16)\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000090", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> most_water([3, 1, 2, 0, 1, 6, 3, 2])\n18\n>>> most_water([1, 2, 6, 5])\n5\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "Two pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\nWhy it works:\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000091", "messages": [{"role": "user", "content": "**Eniten vettä vetävä astia**\n\n`heights[i]` on pystyviivan korkeus kohdassa x = i. Valitse kaksi viivaa, jotka x-akselin kanssa vetävät eniten vettä, ja palauta se määrä (lyhyempi viiva kertaa etäisyys). Viivoja voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> most_water([4, 0, 4, 3, 2])\n9\n>>> most_water([0, 2, 3, 6, 4, 4, 5, 2])\n15\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "\n- Kaikkien parien tarkistaminen on O(n²).\n- Kun lyhyempi viiva on kiinnitetty, jokainen kapeampi astia on huonompi, joten pudota se viiva.\n- Jokainen askel poistaa yhden viivan: lineaarinen aika.\n- Reunatapaukset: alle 2 viivaa, yhtä korkeat viivat, nollat.\n- Vaativuus: O(n) aikaa, O(1) lisämuistia.\n\n\nKaksi osoitinta molemmista päistä; siirrä aina lyhyempää viivaa sisäänpäin, koska sen säilyttäminen voi antaa vain pienempiä astioita.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia.\n\nTestit:\n```python\nassert most_water([4, 0, 4, 3, 2]) == 9\nassert most_water([0, 2, 3, 6, 4, 4, 5, 2]) == 15\nassert most_water([1, 1]) == 1\nassert most_water([5]) == 0\nassert most_water([]) == 0\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.water.container0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000092", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `StreamMedian()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahdesta keskimmäisestä arvosta pienempi. Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nEsimerkki:\n```python\nobj = StreamMedian()\nobj.add(-18)\nobj.median() # -18\nobj.add(2)\nobj.median() # -18\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "\n- Vain keskikohta merkitsee, joten pidä puoliskot erillään järjestetyn listan sijaan.\n- Lisää alempaan puoliskoon, siirrä sen suurin ylempään ja tasapainota niin, että alemmassa on ylimääräinen.\n- Pythonin heapq on minimikeko: tallenna maksimikekoon negatiiviset arvot.\n- Reunatapaukset: yksi luku, toistot, negatiiviset luvut, parillinen ja pariton määrä.\n- Vaativuus: O(log n) per add, O(1) per median, O(n) muistia.\n\n\nKaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia."}], "meta": {"kind": "code.hard.running_median.low", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000093", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(3, [[2, 2], [1, 2], [2, 1], [2, 2], [0, 1], [1, 2], [2, 1], [2, 1]])\nFalse\n>>> can_split_in_two(3, [[2, 2], [0, 2]])\nFalse\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\nWhy it works:\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000094", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(20)\nobj.add(6)\nobj.median() # 13.0\nobj.median() # 13.0\nobj.add(13)\nobj.add(-18)\nobj.median() # 9.5\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000095", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater_circular([4, 3, 4, 4, 4, 0, 2, 0, 4, 3])\n[-1, 4, -1, -1, -1, 2, 4, 4, -1, 4]\n>>> next_greater_circular([5])\n[-1]\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert next_greater_circular([4, 3, 4, 4, 4, 0, 2, 0, 4, 3]) == [-1, 4, -1, -1, -1, 2, 4, 4, -1, 4]\nassert next_greater_circular([5]) == [-1]\nassert next_greater_circular([3, 3, 3]) == [-1, -1, -1]\nassert next_greater_circular([2, 1, 2, 4, 3]) == [4, 2, 4, -1, 4]\nassert next_greater_circular([4, 3, 2, 1]) == [-1, 4, 4, 4]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000096", "messages": [{"role": "user", "content": "**Seuraava suurempi alkio**\n\nPalauta jokaiselle listan `nums` alkiolle ensimmäinen sen oikealla puolella oleva aidosti suurempi arvo, tai -1, jos sellaista ei ole. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> next_greater([8, 9, 2, 9, 5, 5, 3, 1])\n[9, -1, 9, -1, -1, -1, -1, -1]\n>>> next_greater([9, 3, 9, 6])\n[-1, 9, -1, -1]\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia.\n\nTestit:\n```python\nassert next_greater([8, 9, 2, 9, 5, 5, 3, 1]) == [9, -1, 9, -1, -1, -1, -1, -1]\nassert next_greater([9, 3, 9, 6]) == [-1, 9, -1, -1]\nassert next_greater([2, 1, 2, 4, 3]) == [4, 2, 4, -1, -1]\nassert next_greater([3, 3, 3]) == [-1, -1, -1]\nassert next_greater([1, 2, 3, 4]) == [2, 3, 4, -1]\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000097", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> max_container([4, 4])\n4\n>>> max_container([0, 2, 0, 3, 1, 5, 0])\n8\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "Two pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\nWhy it works:\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000098", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> can_split_in_two(5, [[0, 1], [2, 0], [0, 0]])\nFalse\n>>> can_split_in_two(4, [[1, 1], [0, 0]])\nFalse\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "\n- Verkon voi jakaa kahtia täsmälleen silloin, kun siinä ei ole paritonta sykliä.\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n- Reunatapaukset: ei solmuja, erilliset solmut, silmukka, pariton tai parillinen sykli.\n- Vaativuus: O(n + m) aikaa, O(n + m) muistia.\n\n\nVäritä jokainen komponentti kahdella värillä BFS:llä; naapuri, jolla on jo sama väri, todistaa jaon mahdottomaksi.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Vaativuus:** O(n + m) aikaa, O(n + m) muistia.\n\nTestit:\n```python\nassert not can_split_in_two(5, [[0, 1], [2, 0], [0, 0]])\nassert not can_split_in_two(4, [[1, 1], [0, 0]])\nassert can_split_in_two(1, [])\nassert can_split_in_two(0, [])\nassert can_split_in_two(5, [[0, 1], [2, 3]])\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000099", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> circular_next_larger([2, 2, 0, 6, 2, 2])\n[6, 6, 6, -1, 6, 6]\n>>> circular_next_larger([6, 3, 8, 5, 7, 4, 1, 5, 1, 0])\n[8, 8, -1, 7, 8, 5, 5, 6, 6, 6]\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "circular_next_larger", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000100", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(5)\nobj.median() # 5\nobj.median() # 5\nobj.median() # 5\nobj.add(15)\nobj.add(20)\nobj.add(-9)\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(16)\nassert obj.median() == 16\nassert obj.median() == 16\nassert obj.median() == 16\nassert obj.median() == 16\nassert obj.median() == 16\nobj.add(-19)\nobj.add(-18)\nassert obj.median() == -18\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000101", "messages": [{"role": "user", "content": "**Päiviä lämpimämpään päivään**\n\n`temps[i]` on päivän `i` lämpötila. Palauta jokaiselle päivälle, montako päivää pitää odottaa aidosti lämpimämpää päivää, tai 0, jos sellaista ei tule. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> days_until_warmer([8, 8, 4, 4, 9, 3, 0])\n[4, 3, 2, 1, 0, 0, 0]\n>>> days_until_warmer([1, 6, 0, 8, 7, 4, 2, 7, 5, 1])\n[1, 2, 1, 0, 0, 2, 1, 0, 0, 0]\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\nMiksi tämä toimii:\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "days_until_warmer", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000102", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_larger_values([5])\n[-1]\n>>> next_larger_values([9])\n[-1]\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_larger_values", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000103", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('')\n1\n>>> count_decodings('22126221')\n24\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space.\n\nTests:\n```python\nassert count_decodings('') == 1\nassert count_decodings('22126221') == 24\nassert count_decodings('226') == 3\nassert count_decodings('1111111111') == 89\nassert count_decodings('10') == 1\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000104", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('10602')\n0\n>>> count_decodings('2001261')\n0\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000105", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-4)\nobj.add(7)\nobj.add(-18)\nobj.median() # -4\nobj.median() # -4\nobj.add(9)\nobj.median() # 1.5\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000106", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(3, [[0, 1]])\nTrue\n>>> is_bipartite(7, [[1, 0], [1, 5], [3, 3], [4, 1]])\nFalse\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000107", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> trapped_water([])\n0\n>>> trapped_water([5, 3, 2, 1, 3, 3, 5, 0, 6, 0])\n18\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\nWhy it works:\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000108", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([3])\n0\n>>> rain_water([])\n0\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(n) space.\n\n\nThe water above a cell is min(highest wall to its left, highest wall to its right) minus its height; precompute both running maxima.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.water.trap1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000109", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_larger_values([9, 1, 9, 5, 1])\n[-1, 9, -1, -1, -1]\n>>> next_larger_values([2, 4, 6, 7, 5, 4, 5])\n[4, 6, 7, -1, -1, 5, -1]\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert next_larger_values([9, 1, 9, 5, 1]) == [-1, 9, -1, -1, -1]\nassert next_larger_values([2, 4, 6, 7, 5, 4, 5]) == [4, 6, 7, -1, -1, 5, -1]\nassert next_larger_values([4, 3, 2, 1]) == [-1, -1, -1, -1]\nassert next_larger_values([3, 3, 3]) == [-1, -1, -1]\nassert next_larger_values([7]) == [-1]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_larger_values", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000110", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(8)\nobj.median() # 8\nobj.add(13)\nobj.median() # 8\nobj.add(9)\nobj.add(-19)\nobj.add(11)\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000111", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-9)\nobj.add(5)\nobj.median() # -2.0\nobj.add(19)\nobj.median() # 5\nobj.median() # 5\nobj.add(20)\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000112", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> count_decodings('2612210')\n6\n>>> count_decodings('20021011')\n0\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "Dynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000113", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(7, [[3, 2], [3, 6], [0, 4], [1, 2], [5, 3], [4, 0], [4, 0], [2, 6]])\nFalse\n>>> is_bipartite(3, [[0, 1], [1, 1], [1, 0], [1, 2], [2, 1], [1, 1], [1, 1]])\nFalse\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O((n + m) α(n)) time, O(n) space.\n\n\nUnion-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000114", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-18)\nobj.add(1)\nobj.add(-3)\nobj.add(-7)\nobj.median() # -7\nobj.add(-6)\nobj.median() # -6\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000115", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(8, [[3, 3], [2, 5], [6, 6], [6, 0]])\nFalse\n>>> is_bipartite(8, [[4, 6]])\nTrue\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O((n + m) α(n)) time, O(n) space.\n\n\nUnion-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space.\n\nTests:\n```python\nassert not is_bipartite(8, [[3, 3], [2, 5], [6, 6], [6, 0]])\nassert is_bipartite(8, [[4, 6]])\nassert not is_bipartite(3, [[0, 1], [1, 2], [2, 0]])\nassert not is_bipartite(1, [[0, 0]])\nassert is_bipartite(0, [])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000116", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> trapped_water([2, 1, 3, 6, 2, 4, 4, 2])\n3\n>>> trapped_water([3, 3, 5, 4, 4, 1])\n0\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(n) space.\n\n\nThe water above a cell is min(highest wall to its left, highest wall to its right) minus its height; precompute both running maxima.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert trapped_water([2, 1, 3, 6, 2, 4, 4, 2]) == 3\nassert trapped_water([3, 3, 5, 4, 4, 1]) == 0\nassert trapped_water([3, 0, 3]) == 3\nassert trapped_water([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) == 6\nassert trapped_water([2, 0]) == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.water.trap1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000117", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `MedianTracker()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahden keskimmäisen arvon keskiarvo (liukuluku, esim. 2.5). Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nEsimerkki:\n```python\nobj = MedianTracker()\nobj.add(-5)\nobj.add(-17)\nobj.add(11)\nobj.add(-19)\nobj.add(12)\nobj.median() # -5\nobj.median() # -5\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "\n- Vain keskikohta merkitsee, joten pidä puoliskot erillään järjestetyn listan sijaan.\n- Lisää alempaan puoliskoon, siirrä sen suurin ylempään ja tasapainota niin, että alemmassa on ylimääräinen.\n- Pythonin heapq on minimikeko: tallenna maksimikekoon negatiiviset arvot.\n- Reunatapaukset: yksi luku, toistot, negatiiviset luvut, parillinen ja pariton määrä.\n- Vaativuus: O(log n) per add, O(1) per median, O(n) muistia.\n\n\nKaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\nMiksi tämä toimii:\n- Lisää alempaan puoliskoon, siirrä sen suurin ylempään ja tasapainota niin, että alemmassa on ylimääräinen.\n- Pythonin heapq on minimikeko: tallenna maksimikekoon negatiiviset arvot.\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000118", "messages": [{"role": "user", "content": "**Päiviä lämpimämpään päivään**\n\n`temps[i]` on päivän `i` lämpötila. Palauta jokaiselle päivälle, montako päivää pitää odottaa aidosti lämpimämpää päivää, tai 0, jos sellaista ei tule. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> days_until_warmer([9, 8, 4, 6, 5, 4, 9, 3, 1])\n[0, 5, 1, 3, 2, 1, 0, 0, 0]\n>>> days_until_warmer([])\n[]\n```\n\nToteuta se Pythonilla."}, {"role": "assistant", "content": "\n- Jokaisen myöhemmän alkion tarkistaminen on O(n²); jokainen alkio tarvitsee ratkaista vain kerran.\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n- Reunatapaukset: tyhjä lista, yksi alkio, kaikki yhtä suuria, aidosti laskeva.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nMonotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "days_until_warmer", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000119", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-5)\nobj.add(-15)\nobj.add(12)\nobj.add(-1)\nobj.median() # -5\nobj.add(10)\nobj.median() # -1\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000120", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> decode_ways('012112')\n0\n>>> decode_ways('1211200111')\n0\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(1) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Vaativuus:** O(n) aikaa, O(1) muistia.\n\nTestit:\n```python\nassert decode_ways('012112') == 0\nassert decode_ways('1211200111') == 0\nassert decode_ways('') == 1\nassert decode_ways('1111111111') == 89\nassert decode_ways('226') == 3\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000121", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-4)\nobj.add(11)\nobj.median() # 3.5\nobj.add(20)\nobj.add(-15)\nobj.add(1)\nobj.add(8)\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000122", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> most_water([0, 4, 1])\n1\n>>> most_water([3, 3, 0, 1, 1, 3])\n15\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "Two pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\nWhy it works:\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000123", "messages": [{"role": "user", "content": "**Seuraava suurempi alkio kehällä**\n\n`nums` on kehämäinen: viimeisen alkion jälkeen tulee taas ensimmäinen. Palauta jokaiselle alkiolle ensimmäinen aidosti suurempi arvo eteenpäin kulkien (kehän ympäri), tai -1, jos sellaista ei ole. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> next_greater_circular([5, 0, 8, 4, 0, 2, 6, 0])\n[8, 8, -1, 6, 2, 6, 8, 5]\n>>> next_greater_circular([8, 3])\n[-1, 8]\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "\n- Jokaisen myöhemmän alkion tarkistaminen on O(n²); jokainen alkio tarvitsee ratkaista vain kerran.\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n- Reunatapaukset: tyhjä lista, yksi alkio, kaikki yhtä suuria, aidosti laskeva.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nMonotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle. Kaksi kierrosta taulukon yli hoitaa kehän.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\nMiksi tämä toimii:\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000124", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> most_water([5, 0, 3, 4, 4, 5])\n25\n>>> most_water([1, 5, 2, 4, 6, 6])\n20\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "Two pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000125", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> is_bipartite(8, [])\nTrue\n>>> is_bipartite(4, [[1, 3], [2, 3]])\nTrue\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "\n- Verkon voi jakaa kahtia täsmälleen silloin, kun siinä ei ole paritonta sykliä.\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n- Reunatapaukset: ei solmuja, erilliset solmut, silmukka, pariton tai parillinen sykli.\n- Vaativuus: O((n + m) α(n)) aikaa, O(n) muistia.\n\n\nUnion-find solmuille ja niiden vastakkaisille puolille: kaari u-v yhdistää u:n ja ei-v:n sekä v:n ja ei-u:n; jos u ja v päätyvät samaan joukkoon, jako on mahdoton.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Vaativuus:** O((n + m) α(n)) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000126", "messages": [{"role": "user", "content": "**Päiviä lämpimämpään päivään**\n\n`temps[i]` on päivän `i` lämpötila. Palauta jokaiselle päivälle, montako päivää pitää odottaa aidosti lämpimämpää päivää, tai 0, jos sellaista ei tule. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> steps_to_greater([9, 6, 7, 7, 6, 8])\n[0, 1, 3, 2, 1, 0]\n>>> steps_to_greater([2, 1, 1, 3, 7])\n[3, 2, 1, 1, 0]\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia.\n\nTestit:\n```python\nassert steps_to_greater([9, 6, 7, 7, 6, 8]) == [0, 1, 3, 2, 1, 0]\nassert steps_to_greater([2, 1, 1, 3, 7]) == [3, 2, 1, 1, 0]\nassert steps_to_greater([4, 3, 2, 1]) == [0, 0, 0, 0]\nassert steps_to_greater([7]) == [0]\nassert steps_to_greater([2, 1, 2, 4, 3]) == [3, 1, 1, 0, 0]\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "steps_to_greater", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000127", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('2020621211')\n8\n>>> count_decodings('22622226112')\n72\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000128", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-16)\nobj.median() # -16\nobj.add(-17)\nobj.median() # -17\nobj.add(-19)\nobj.add(-4)\nobj.add(11)\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(-16)\nassert obj.median() == -16\nassert obj.median() == -16\nassert obj.median() == -16\nassert obj.median() == -16\nassert obj.median() == -16\nassert obj.median() == -16\nobj.add(17)\nobj.add(7)\nobj.add(9)\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000129", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(13)\nobj.add(-8)\nobj.median() # -8\nobj.median() # -8\nobj.add(-15)\nobj.add(17)\nobj.add(10)\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(16)\nobj.add(-19)\nobj.add(13)\nassert obj.median() == 13\nobj.add(-19)\nobj.add(20)\nassert obj.median() == 13\nobj.add(16)\nobj.add(-13)\nassert obj.median() == 13\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000130", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(1, [[0, 0], [0, 0]])\nFalse\n>>> can_split_in_two(7, [])\nTrue\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O((n + m) α(n)) time, O(n) space.\n\n\nUnion-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\nWhy it works:\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000131", "messages": [{"role": "user", "content": "**Days until a warmer day**\n\n`temps[i]` is the temperature on day `i`. For each day, return how many days you have to wait for a strictly warmer day, or 0 if no warmer day comes. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> days_until_warmer([4, 9, 7])\n[1, 0, 0]\n>>> days_until_warmer([7])\n[0]\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "days_until_warmer", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000132", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> can_split_in_two(2, [[0, 0], [0, 0], [0, 0]])\nFalse\n>>> can_split_in_two(3, [[1, 2], [1, 2], [1, 1]])\nFalse\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "Väritä jokainen komponentti kahdella värillä BFS:llä; naapuri, jolla on jo sama väri, todistaa jaon mahdottomaksi.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Vaativuus:** O(n + m) aikaa, O(n + m) muistia.\n\nTestit:\n```python\nassert not can_split_in_two(2, [[0, 0], [0, 0], [0, 0]])\nassert not can_split_in_two(3, [[1, 2], [1, 2], [1, 1]])\nassert can_split_in_two(1, [])\nassert can_split_in_two(5, [[0, 1], [2, 3]])\nassert can_split_in_two(0, [])\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000133", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> most_water([0, 6, 6, 5, 1, 0, 3, 5, 3])\n30\n>>> most_water([0, 4])\n0\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- Checking all pairs is O(n²).\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n- Edge cases: fewer than 2 lines, equal heights, zeros.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\nWhy it works:\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000134", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `StreamMedian()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahden keskimmäisen arvon keskiarvo (liukuluku, esim. 2.5). Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nEsimerkki:\n```python\nobj = StreamMedian()\nobj.add(1)\nobj.add(-18)\nobj.add(-3)\nobj.add(2)\nobj.median() # -1.0\nobj.median() # -1.0\nobj.median() # -1.0\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "Kaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000135", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-16)\nobj.add(17)\nobj.add(3)\nobj.median() # 3\nobj.median() # 3\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(-18)\nobj.add(10)\nassert obj.median() == -18\nobj.add(-8)\nobj.add(-19)\nassert obj.median() == -18\nassert obj.median() == -18\nobj.add(-2)\nassert obj.median() == -8\nassert obj.median() == -8\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000136", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> is_bipartite(3, [[2, 1], [1, 1]])\nFalse\n>>> is_bipartite(6, [[3, 3], [5, 4]])\nFalse\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "\n- Verkon voi jakaa kahtia täsmälleen silloin, kun siinä ei ole paritonta sykliä.\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n- Reunatapaukset: ei solmuja, erilliset solmut, silmukka, pariton tai parillinen sykli.\n- Vaativuus: O((n + m) α(n)) aikaa, O(n) muistia.\n\n\nUnion-find solmuille ja niiden vastakkaisille puolille: kaari u-v yhdistää u:n ja ei-v:n sekä v:n ja ei-u:n; jos u ja v päätyvät samaan joukkoon, jako on mahdoton.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Vaativuus:** O((n + m) α(n)) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000137", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> circular_next_larger([1, 5, 8, 4, 2, 5, 7, 5, 0, 9])\n[5, 8, 9, 5, 5, 7, 9, 9, 9, -1]\n>>> circular_next_larger([5, 0, 6, 0, 3])\n[6, 6, -1, 3, 5]\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\nWhy it works:\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "circular_next_larger", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000138", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('22106212161')\n16\n>>> count_decodings('2106021')\n0\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000139", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater_circular([8, 4])\n[-1, 8]\n>>> next_greater_circular([5, 3])\n[-1, 5]\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\nWhy it works:\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000140", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater([3, 5, 4, 5, 3, 7, 9, 1, 1, 5])\n[5, 7, 5, 7, 7, 9, -1, 5, 5, -1]\n>>> next_greater([4, 7, 6, 8, 0, 5])\n[7, 8, 8, -1, 5, -1]\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000141", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> count_decodings('1200110210')\n0\n>>> count_decodings('26210122')\n6\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(1) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nMiksi tämä toimii:\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n\n**Vaativuus:** O(n) aikaa, O(1) muistia."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000142", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-15)\nobj.median() # -15\nobj.add(-4)\nobj.add(20)\nobj.median() # -4\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\nWhy it works:\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000143", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> count_decodings('221022220')\n6\n>>> count_decodings('22')\n2\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia.\n\nTestit:\n```python\nassert count_decodings('221022220') == 6\nassert count_decodings('22') == 2\nassert count_decodings('10') == 1\nassert count_decodings('27') == 1\nassert count_decodings('226') == 3\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000144", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> trapped_water([3])\n0\n>>> trapped_water([3, 6, 2, 0])\n0\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000145", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(4, [[0, 1], [2, 1], [2, 2], [3, 0], [0, 3], [1, 1], [1, 1], [0, 2]])\nFalse\n>>> can_split_in_two(8, [[7, 5], [7, 0], [4, 3], [2, 1], [2, 7], [6, 2], [3, 5], [5, 2]])\nFalse\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000146", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater_circular([7, 9, 6, 0])\n[9, -1, 7, 7]\n>>> next_greater_circular([6, 3])\n[-1, 6]\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000147", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(5, [[4, 4], [3, 4], [0, 2], [3, 1]])\nFalse\n>>> is_bipartite(8, [[0, 2], [7, 3], [6, 2], [1, 5]])\nTrue\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000148", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('2611222')\n16\n>>> count_decodings('261102101162')\n6\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000149", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(4, [[3, 2], [3, 1], [0, 1]])\nTrue\n>>> is_bipartite(4, [[3, 2], [2, 3], [3, 0], [0, 2], [3, 2], [2, 0], [1, 1], [0, 0]])\nFalse\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\nWhy it works:\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000150", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('11')\n2\n>>> decode_ways('112061200162')\n0\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space.\n\nTests:\n```python\nassert decode_ways('11') == 2\nassert decode_ways('112061200162') == 0\nassert decode_ways('10') == 1\nassert decode_ways('100') == 0\nassert decode_ways('226') == 3\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000151", "messages": [{"role": "user", "content": "**Päiviä lämpimämpään päivään**\n\n`temps[i]` on päivän `i` lämpötila. Palauta jokaiselle päivälle, montako päivää pitää odottaa aidosti lämpimämpää päivää, tai 0, jos sellaista ei tule. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> days_until_warmer([8, 3, 2, 9, 7, 6, 3, 5, 3])\n[3, 2, 1, 0, 0, 0, 1, 0, 0]\n>>> days_until_warmer([6, 2, 3, 9, 4, 0, 8, 9, 2])\n[3, 1, 1, 0, 2, 1, 1, 0, 0]\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "\n- Jokaisen myöhemmän alkion tarkistaminen on O(n²); jokainen alkio tarvitsee ratkaista vain kerran.\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n- Reunatapaukset: tyhjä lista, yksi alkio, kaikki yhtä suuria, aidosti laskeva.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nMonotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\nMiksi tämä toimii:\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "days_until_warmer", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000152", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater_circular([])\n[]\n>>> next_greater_circular([5])\n[-1]\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000153", "messages": [{"role": "user", "content": "**Days until a warmer day**\n\n`temps[i]` is the temperature on day `i`. For each day, return how many days you have to wait for a strictly warmer day, or 0 if no warmer day comes. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> steps_to_greater([0, 7, 0, 5, 9, 5, 2, 9, 8])\n[1, 3, 1, 1, 0, 2, 1, 0, 0]\n>>> steps_to_greater([5, 1, 2, 9, 9, 7, 9, 7])\n[3, 1, 1, 0, 0, 1, 0, 0]\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "steps_to_greater", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000154", "messages": [{"role": "user", "content": "**Eniten vettä vetävä astia**\n\n`heights[i]` on pystyviivan korkeus kohdassa x = i. Valitse kaksi viivaa, jotka x-akselin kanssa vetävät eniten vettä, ja palauta se määrä (lyhyempi viiva kertaa etäisyys). Viivoja voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> most_water([3, 1, 1, 0, 6, 6])\n15\n>>> most_water([3, 6, 5, 6, 0])\n12\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "\n- Kaikkien parien tarkistaminen on O(n²).\n- Kun lyhyempi viiva on kiinnitetty, jokainen kapeampi astia on huonompi, joten pudota se viiva.\n- Jokainen askel poistaa yhden viivan: lineaarinen aika.\n- Reunatapaukset: alle 2 viivaa, yhtä korkeat viivat, nollat.\n- Vaativuus: O(n) aikaa, O(1) lisämuistia.\n\n\nKaksi osoitinta molemmista päistä; siirrä aina lyhyempää viivaa sisäänpäin, koska sen säilyttäminen voi antaa vain pienempiä astioita.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\nMiksi tämä toimii:\n- Kun lyhyempi viiva on kiinnitetty, jokainen kapeampi astia on huonompi, joten pudota se viiva.\n- Jokainen askel poistaa yhden viivan: lineaarinen aika.\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia."}], "meta": {"kind": "code.hard.water.container0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000155", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(6)\nobj.add(-3)\nobj.add(-1)\nobj.median() # -1\nobj.add(-5)\nobj.median() # -2.0\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(12)\nassert obj.median() == 12\nassert obj.median() == 12\nassert obj.median() == 12\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000156", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('02202121')\n0\n>>> count_decodings('210022')\n0\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert count_decodings('02202121') == 0\nassert count_decodings('210022') == 0\nassert count_decodings('10') == 1\nassert count_decodings('27') == 1\nassert count_decodings('1111111111') == 89\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000157", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(3)\nobj.add(-10)\nobj.add(13)\nobj.median() # 3\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000158", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(6, [[0, 4], [2, 1], [1, 4], [0, 0], [5, 5], [1, 3], [4, 4], [1, 1]])\nFalse\n>>> can_split_in_two(4, [[2, 1], [0, 0], [1, 1]])\nFalse\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O((n + m) α(n)) time, O(n) space.\n\n\nUnion-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space.\n\nTests:\n```python\nassert not can_split_in_two(6, [[0, 4], [2, 1], [1, 4], [0, 0], [5, 5], [1, 3], [4, 4], [1, 1]])\nassert not can_split_in_two(4, [[2, 1], [0, 0], [1, 1]])\nassert can_split_in_two(5, [[0, 1], [2, 3]])\nassert can_split_in_two(4, [[0, 1], [1, 2], [2, 3], [3, 0]])\nassert not can_split_in_two(3, [[0, 1], [1, 2], [2, 0]])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000159", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('22001021010')\n0\n>>> decode_ways('220')\n1\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(n) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert decode_ways('22001021010') == 0\nassert decode_ways('220') == 1\nassert decode_ways('226') == 3\nassert decode_ways('27') == 1\nassert decode_ways('') == 1\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000160", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-15)\nobj.median() # -15\nobj.median() # -15\nobj.median() # -15\nobj.add(-18)\nobj.median() # -18\nobj.add(-14)\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\nWhy it works:\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000161", "messages": [{"role": "user", "content": "**Päiviä lämpimämpään päivään**\n\n`temps[i]` on päivän `i` lämpötila. Palauta jokaiselle päivälle, montako päivää pitää odottaa aidosti lämpimämpää päivää, tai 0, jos sellaista ei tule. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> days_until_warmer([8, 7, 1, 4, 9, 5, 0, 8, 8, 7])\n[4, 3, 1, 1, 0, 2, 1, 0, 0, 0]\n>>> days_until_warmer([5, 2, 3, 9, 8, 7, 6, 5])\n[3, 1, 1, 0, 0, 0, 0, 0]\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "days_until_warmer", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000162", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('00')\n0\n>>> count_decodings('')\n1\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space.\n\nTests:\n```python\nassert count_decodings('00') == 0\nassert count_decodings('') == 1\nassert count_decodings('') == 1\nassert count_decodings('100') == 0\nassert count_decodings('1111111111') == 89\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000163", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('2')\n1\n>>> count_decodings('22222262')\n21\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000164", "messages": [{"role": "user", "content": "**Eniten vettä vetävä astia**\n\n`heights[i]` on pystyviivan korkeus kohdassa x = i. Valitse kaksi viivaa, jotka x-akselin kanssa vetävät eniten vettä, ja palauta se määrä (lyhyempi viiva kertaa etäisyys). Viivoja voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> most_water([3, 6, 4, 2, 2, 4, 6, 0])\n30\n>>> most_water([4, 0, 5, 2, 0, 6, 2, 5])\n28\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "Kaksi osoitinta molemmista päistä; siirrä aina lyhyempää viivaa sisäänpäin, koska sen säilyttäminen voi antaa vain pienempiä astioita.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia."}], "meta": {"kind": "code.hard.water.container0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000165", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([3, 2, 1, 6, 1, 0])\n3\n>>> rain_water([])\n0\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "The water above a cell is min(highest wall to its left, highest wall to its right) minus its height; precompute both running maxima.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert rain_water([3, 2, 1, 6, 1, 0]) == 3\nassert rain_water([]) == 0\nassert rain_water([2, 0]) == 0\nassert rain_water([4, 2, 0, 3, 2, 5]) == 9\nassert rain_water([3, 0, 3]) == 3\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.water.trap1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000166", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('1622610')\n6\n>>> decode_ways('26262220')\n8\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space.\n\nTests:\n```python\nassert decode_ways('1622610') == 6\nassert decode_ways('26262220') == 8\nassert decode_ways('226') == 3\nassert decode_ways('0') == 0\nassert decode_ways('') == 1\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000167", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([3, 0, 4, 5, 6])\n3\n>>> rain_water([1, 3, 1, 3, 1, 5, 6, 1])\n4\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(n) space.\n\n\nThe water above a cell is min(highest wall to its left, highest wall to its right) minus its height; precompute both running maxima.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.water.trap1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000168", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-9)\nobj.add(1)\nobj.median() # -9\nobj.median() # -9\nobj.add(20)\nobj.median() # 1\nobj.add(19)\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000169", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('222212011211')\n64\n>>> count_decodings('160262')\n0\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000170", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(4, [[3, 1], [0, 3]])\nTrue\n>>> is_bipartite(1, [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]])\nFalse\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\nWhy it works:\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000171", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('11622001')\n0\n>>> count_decodings('261610')\n4\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000172", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(19)\nobj.add(8)\nobj.add(5)\nobj.add(-12)\nobj.add(-9)\nobj.add(15)\nobj.add(-18)\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000173", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(4)\nobj.add(-14)\nobj.add(1)\nobj.median() # 1\nobj.add(-12)\nobj.median() # -5.5\nobj.median() # -5.5\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(19)\nassert obj.median() == 19\nobj.add(16)\nassert obj.median() == 17.5\nobj.add(-10)\nassert obj.median() == 16\nassert obj.median() == 16\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000174", "messages": [{"role": "user", "content": "**Days until a warmer day**\n\n`temps[i]` is the temperature on day `i`. For each day, return how many days you have to wait for a strictly warmer day, or 0 if no warmer day comes. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> steps_to_greater([2, 9, 1])\n[1, 0, 0]\n>>> steps_to_greater([5, 9, 4, 0, 9, 9, 8])\n[1, 0, 2, 1, 0, 0, 0]\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert steps_to_greater([2, 9, 1]) == [1, 0, 0]\nassert steps_to_greater([5, 9, 4, 0, 9, 9, 8]) == [1, 0, 2, 1, 0, 0, 0]\nassert steps_to_greater([2, 1, 2, 4, 3]) == [3, 1, 1, 0, 0]\nassert steps_to_greater([3, 3, 3]) == [0, 0, 0]\nassert steps_to_greater([7]) == [0]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "steps_to_greater", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000175", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater([4, 1, 2, 3])\n[-1, 2, 3, -1]\n>>> next_greater([7, 9, 9, 4, 8, 9, 6, 4, 6])\n[9, -1, -1, 8, 9, -1, -1, 6, -1]\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\nWhy it works:\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000176", "messages": [{"role": "user", "content": "**Days until a warmer day**\n\n`temps[i]` is the temperature on day `i`. For each day, return how many days you have to wait for a strictly warmer day, or 0 if no warmer day comes. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> days_until_warmer([])\n[]\n>>> days_until_warmer([8])\n[0]\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert days_until_warmer([]) == []\nassert days_until_warmer([8]) == [0]\nassert days_until_warmer([2, 1, 2, 4, 3]) == [3, 1, 1, 0, 0]\nassert days_until_warmer([1, 2, 3, 4]) == [1, 1, 1, 0]\nassert days_until_warmer([3, 3, 3]) == [0, 0, 0]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "days_until_warmer", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000177", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('0212')\n0\n>>> count_decodings('1221')\n5\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space.\n\nTests:\n```python\nassert count_decodings('0212') == 0\nassert count_decodings('1221') == 5\nassert count_decodings('27') == 1\nassert count_decodings('10') == 1\nassert count_decodings('0') == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000178", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-7)\nobj.add(-11)\nobj.median() # -9.0\nobj.median() # -9.0\nobj.add(17)\nobj.add(-11)\nobj.median() # -9.0\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000179", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('')\n1\n>>> count_decodings('21221')\n8\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(n) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert count_decodings('') == 1\nassert count_decodings('21221') == 8\nassert count_decodings('226') == 3\nassert count_decodings('27') == 1\nassert count_decodings('0') == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000180", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-10)\nobj.median() # -10\nobj.median() # -10\nobj.add(-9)\nobj.median() # -9.5\nobj.median() # -9.5\nobj.median() # -9.5\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000181", "messages": [{"role": "user", "content": "**Seuraava suurempi alkio kehällä**\n\n`nums` on kehämäinen: viimeisen alkion jälkeen tulee taas ensimmäinen. Palauta jokaiselle alkiolle ensimmäinen aidosti suurempi arvo eteenpäin kulkien (kehän ympäri), tai -1, jos sellaista ei ole. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> next_greater_circular([9, 1, 1, 8, 3, 9])\n[-1, 8, 8, 9, 9, -1]\n>>> next_greater_circular([])\n[]\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "\n- Jokaisen myöhemmän alkion tarkistaminen on O(n²); jokainen alkio tarvitsee ratkaista vain kerran.\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n- Reunatapaukset: tyhjä lista, yksi alkio, kaikki yhtä suuria, aidosti laskeva.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nMonotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle. Kaksi kierrosta taulukon yli hoitaa kehän.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000182", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> can_split_in_two(4, [[2, 2], [2, 3], [1, 1], [2, 1], [0, 3], [0, 3], [2, 3], [1, 2]])\nFalse\n>>> can_split_in_two(6, [[1, 2], [4, 5], [0, 0], [3, 2], [1, 5], [1, 4]])\nFalse\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "Väritä jokainen komponentti kahdella värillä BFS:llä; naapuri, jolla on jo sama väri, todistaa jaon mahdottomaksi.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Vaativuus:** O(n + m) aikaa, O(n + m) muistia.\n\nTestit:\n```python\nassert not can_split_in_two(4, [[2, 2], [2, 3], [1, 1], [2, 1], [0, 3], [0, 3], [2, 3], [1, 2]])\nassert not can_split_in_two(6, [[1, 2], [4, 5], [0, 0], [3, 2], [1, 5], [1, 4]])\nassert not can_split_in_two(1, [[0, 0]])\nassert can_split_in_two(4, [[0, 1], [1, 2], [2, 3], [3, 0]])\nassert can_split_in_two(0, [])\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000183", "messages": [{"role": "user", "content": "**Seuraava suurempi alkio kehällä**\n\n`nums` on kehämäinen: viimeisen alkion jälkeen tulee taas ensimmäinen. Palauta jokaiselle alkiolle ensimmäinen aidosti suurempi arvo eteenpäin kulkien (kehän ympäri), tai -1, jos sellaista ei ole. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> next_greater_circular([7, 4, 5, 8, 9, 0, 4])\n[8, 5, 8, 9, -1, 4, 7]\n>>> next_greater_circular([4, 5, 1, 1])\n[5, -1, 4, 4]\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "\n- Jokaisen myöhemmän alkion tarkistaminen on O(n²); jokainen alkio tarvitsee ratkaista vain kerran.\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n- Reunatapaukset: tyhjä lista, yksi alkio, kaikki yhtä suuria, aidosti laskeva.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nMonotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle. Kaksi kierrosta taulukon yli hoitaa kehän.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000184", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> is_bipartite(6, [[1, 5], [0, 0], [1, 3], [5, 5]])\nFalse\n>>> is_bipartite(8, [[2, 1], [0, 6], [3, 7], [3, 4]])\nTrue\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "\n- Verkon voi jakaa kahtia täsmälleen silloin, kun siinä ei ole paritonta sykliä.\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n- Reunatapaukset: ei solmuja, erilliset solmut, silmukka, pariton tai parillinen sykli.\n- Vaativuus: O(n + m) aikaa, O(n + m) muistia.\n\n\nVäritä jokainen komponentti kahdella värillä BFS:llä; naapuri, jolla on jo sama väri, todistaa jaon mahdottomaksi.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Vaativuus:** O(n + m) aikaa, O(n + m) muistia."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000185", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> can_split_in_two(8, [])\nTrue\n>>> can_split_in_two(5, [[2, 3], [0, 1], [0, 3], [1, 4], [3, 1], [4, 0], [4, 4], [1, 2]])\nFalse\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "\n- Verkon voi jakaa kahtia täsmälleen silloin, kun siinä ei ole paritonta sykliä.\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n- Reunatapaukset: ei solmuja, erilliset solmut, silmukka, pariton tai parillinen sykli.\n- Vaativuus: O((n + m) α(n)) aikaa, O(n) muistia.\n\n\nUnion-find solmuille ja niiden vastakkaisille puolille: kaari u-v yhdistää u:n ja ei-v:n sekä v:n ja ei-u:n; jos u ja v päätyvät samaan joukkoon, jako on mahdoton.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\nMiksi tämä toimii:\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n\n**Vaativuus:** O((n + m) α(n)) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000186", "messages": [{"role": "user", "content": "**Days until a warmer day**\n\n`temps[i]` is the temperature on day `i`. For each day, return how many days you have to wait for a strictly warmer day, or 0 if no warmer day comes. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> days_until_warmer([6, 0, 8])\n[2, 1, 0]\n>>> days_until_warmer([3, 0, 6])\n[2, 1, 0]\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "days_until_warmer", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000187", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(4, [[2, 0], [2, 3], [1, 0], [3, 3], [0, 3], [3, 3]])\nFalse\n>>> can_split_in_two(7, [])\nTrue\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O((n + m) α(n)) time, O(n) space.\n\n\nUnion-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space.\n\nTests:\n```python\nassert not can_split_in_two(4, [[2, 0], [2, 3], [1, 0], [3, 3], [0, 3], [3, 3]])\nassert can_split_in_two(7, [])\nassert can_split_in_two(0, [])\nassert can_split_in_two(1, [])\nassert can_split_in_two(5, [[0, 1], [2, 3]])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000188", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('106121010121')\n6\n>>> count_decodings('2611611')\n12\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000189", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(5, [[1, 4], [2, 4], [1, 3], [1, 2]])\nFalse\n>>> is_bipartite(1, [])\nTrue\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space.\n\nTests:\n```python\nassert not is_bipartite(5, [[1, 4], [2, 4], [1, 3], [1, 2]])\nassert is_bipartite(1, [])\nassert is_bipartite(1, [])\nassert is_bipartite(4, [[0, 1], [1, 2], [2, 3], [3, 0]])\nassert not is_bipartite(3, [[0, 1], [1, 2], [2, 0]])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000190", "messages": [{"role": "user", "content": "**Sadeveden kertyminen**\n\n`heights[i]` on 1 leveän seinäosan korkeus. Sateen jälkeen vettä kertyy korkeampien osien väliin. Palauta kertyneen veden kokonaismäärä. Osia voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> trapped_water([])\n0\n>>> trapped_water([])\n0\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "\n- Vesi kohdassa i = min(maksimi vasemmalla, maksimi oikealla) - heights[i], ei koskaan negatiivinen.\n- Molempien maksimien laskeminen joka i:lle on O(n²).\n- Juoksevat maksimit (tai kaksi osoitinta) antavat jokaisen tason lineaarisessa ajassa.\n- Reunatapaukset: tyhjä lista, alle 3 seinää, tasainen tai monotoninen profiili.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nRuudun yllä oleva vesi on min(korkein seinä vasemmalla, korkein seinä oikealla) miinus sen korkeus; laske molemmat juoksevat maksimit etukäteen.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.water.trap1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000191", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> circular_next_larger([3, 9])\n[9, -1]\n>>> circular_next_larger([4, 6, 8, 0, 8, 3, 5, 3, 1])\n[6, 8, -1, 8, -1, 5, 6, 4, 4]\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert circular_next_larger([3, 9]) == [9, -1]\nassert circular_next_larger([4, 6, 8, 0, 8, 3, 5, 3, 1]) == [6, 8, -1, 8, -1, 5, 6, 4, 4]\nassert circular_next_larger([1, 2, 3, 4]) == [2, 3, 4, -1]\nassert circular_next_larger([3, 3, 3]) == [-1, -1, -1]\nassert circular_next_larger([2, 1, 2, 4, 3]) == [4, 2, 4, -1, 4]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "circular_next_larger", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000192", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_larger_values([0, 3, 6])\n[3, 6, -1]\n>>> next_larger_values([5, 5])\n[-1, -1]\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert next_larger_values([0, 3, 6]) == [3, 6, -1]\nassert next_larger_values([5, 5]) == [-1, -1]\nassert next_larger_values([]) == []\nassert next_larger_values([2, 1, 2, 4, 3]) == [4, 2, 4, -1, -1]\nassert next_larger_values([7]) == [-1]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_larger_values", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000193", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> trapped_water([0])\n0\n>>> trapped_water([])\n0\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "The water above a cell is min(highest wall to its left, highest wall to its right) minus its height; precompute both running maxima.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\nWhy it works:\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.water.trap1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000194", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(4)\nobj.add(-3)\nobj.add(12)\nobj.median() # 4\nobj.median() # 4\nobj.median() # 4\nobj.median() # 4\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000195", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([1, 4, 2, 1, 5, 3, 4, 1])\n6\n>>> rain_water([1])\n0\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\nWhy it works:\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000196", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `MedianTracker()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahdesta keskimmäisestä arvosta pienempi. Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nEsimerkki:\n```python\nobj = MedianTracker()\nobj.add(14)\nobj.add(17)\nobj.add(6)\nobj.add(9)\nobj.add(-8)\nobj.median() # 9\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "Kaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia."}], "meta": {"kind": "code.hard.running_median.low", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000197", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> most_water([6])\n0\n>>> most_water([2])\n0\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- Checking all pairs is O(n²).\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n- Edge cases: fewer than 2 lines, equal heights, zeros.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\nWhy it works:\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000198", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('11220111')\n9\n>>> decode_ways('12')\n2\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000199", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([2, 5, 5, 2, 2])\n0\n>>> rain_water([0, 0, 2, 5])\n0\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "The water above a cell is min(highest wall to its left, highest wall to its right) minus its height; precompute both running maxima.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.water.trap1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000200", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-3)\nobj.median() # -3\nobj.add(-15)\nobj.median() # -15\nobj.add(13)\nobj.add(6)\nobj.median() # -3\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(-20)\nobj.add(-17)\nassert obj.median() == -20\nobj.add(6)\nassert obj.median() == -17\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000201", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> can_split_in_two(1, [[0, 0], [0, 0], [0, 0], [0, 0]])\nFalse\n>>> can_split_in_two(2, [])\nTrue\n```\n\nToteuta se Pythonilla."}, {"role": "assistant", "content": "\n- Verkon voi jakaa kahtia täsmälleen silloin, kun siinä ei ole paritonta sykliä.\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n- Reunatapaukset: ei solmuja, erilliset solmut, silmukka, pariton tai parillinen sykli.\n- Vaativuus: O(n + m) aikaa, O(n + m) muistia.\n\n\nVäritä jokainen komponentti kahdella värillä BFS:llä; naapuri, jolla on jo sama väri, todistaa jaon mahdottomaksi.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Vaativuus:** O(n + m) aikaa, O(n + m) muistia."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000202", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('2222612261')\n40\n>>> count_decodings('600201')\n0\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000203", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('6262022212')\n16\n>>> decode_ways('22162121')\n25\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000204", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `MedianTracker()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahdesta keskimmäisestä arvosta pienempi. Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nEsimerkki:\n```python\nobj = MedianTracker()\nobj.add(-17)\nobj.median() # -17\nobj.add(3)\nobj.add(19)\nobj.add(9)\nobj.median() # 3\nobj.median() # 3\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "Kaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia.\n\nTestit:\n```python\nobj = MedianTracker()\nobj.add(-17)\nobj.add(10)\nobj.add(16)\nobj.add(7)\nassert obj.median() == 7\nassert obj.median() == 7\nobj.add(11)\nassert obj.median() == 10\n\nobj = MedianTracker()\nobj.add(5)\nassert obj.median() == 5\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.running_median.low", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000205", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-10)\nobj.median() # -10\nobj.add(-8)\nobj.median() # -10\nobj.add(-11)\nobj.add(-10)\nobj.median() # -10\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000206", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(8, [])\nTrue\n>>> is_bipartite(5, [[4, 1], [0, 3]])\nTrue\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O((n + m) α(n)) time, O(n) space.\n\n\nUnion-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000207", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> count_decodings('60121060')\n0\n>>> count_decodings('22266')\n5\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(1) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Vaativuus:** O(n) aikaa, O(1) muistia."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000208", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> decode_ways('212220126')\n15\n>>> decode_ways('2261112')\n15\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "Dynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nMiksi tämä toimii:\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n\n**Vaativuus:** O(n) aikaa, O(1) muistia."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000209", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(20)\nobj.add(-10)\nobj.median() # -10\nobj.add(10)\nobj.median() # 10\nobj.median() # 10\nobj.add(8)\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(1)\nobj.add(-20)\nobj.add(-12)\nassert obj.median() == -12\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000210", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(5, [[0, 3], [3, 0], [0, 0], [1, 4], [3, 3], [3, 0]])\nFalse\n>>> is_bipartite(8, [])\nTrue\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Two-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000211", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([4, 4, 2, 3, 5, 0])\n3\n>>> rain_water([1])\n0\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(n) space.\n\n\nThe water above a cell is min(highest wall to its left, highest wall to its right) minus its height; precompute both running maxima.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.water.trap1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000212", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-16)\nobj.median() # -16\nobj.median() # -16\nobj.median() # -16\nobj.median() # -16\nobj.median() # -16\nobj.median() # -16\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000213", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(7, [])\nTrue\n>>> can_split_in_two(3, [[2, 0], [2, 2], [0, 2], [0, 2]])\nFalse\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O((n + m) α(n)) time, O(n) space.\n\n\nUnion-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space.\n\nTests:\n```python\nassert can_split_in_two(7, [])\nassert not can_split_in_two(3, [[2, 0], [2, 2], [0, 2], [0, 2]])\nassert can_split_in_two(5, [[0, 1], [2, 3]])\nassert not can_split_in_two(1, [[0, 0]])\nassert not can_split_in_two(3, [[0, 1], [1, 2], [2, 0]])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000214", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-15)\nobj.add(1)\nobj.median() # -15\nobj.median() # -15\nobj.add(-13)\nobj.add(3)\nobj.add(-10)\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000215", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(3, [[0, 2], [0, 0], [2, 1], [2, 1]])\nFalse\n>>> can_split_in_two(8, [[0, 2], [2, 2], [5, 5], [1, 3]])\nFalse\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space.\n\nTests:\n```python\nassert not can_split_in_two(3, [[0, 2], [0, 0], [2, 1], [2, 1]])\nassert not can_split_in_two(8, [[0, 2], [2, 2], [5, 5], [1, 3]])\nassert can_split_in_two(4, [[0, 1], [1, 2], [2, 3], [3, 0]])\nassert can_split_in_two(0, [])\nassert not can_split_in_two(3, [[0, 1], [1, 2], [2, 0]])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000216", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('201202')\n1\n>>> decode_ways('2211')\n5\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000217", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(7, [[4, 0], [6, 5], [3, 2], [6, 6], [6, 3]])\nFalse\n>>> is_bipartite(7, [[0, 1], [6, 3], [5, 5], [4, 6]])\nFalse\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000218", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('6222122621')\n42\n>>> count_decodings('226262062')\n6\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space.\n\nTests:\n```python\nassert count_decodings('6222122621') == 42\nassert count_decodings('226262062') == 6\nassert count_decodings('226') == 3\nassert count_decodings('0') == 0\nassert count_decodings('1111111111') == 89\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000219", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> decode_ways('212226')\n13\n>>> decode_ways('')\n1\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "Dynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\nMiksi tämä toimii:\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000220", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> circular_next_larger([3, 2, 4, 9, 4])\n[4, 4, 9, -1, 9]\n>>> circular_next_larger([8, 8, 1, 7, 0])\n[-1, -1, 7, 8, 8]\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\nWhy it works:\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "circular_next_larger", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000221", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('126222')\n9\n>>> decode_ways('662112022')\n6\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(n) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000222", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(18)\nobj.median() # 18\nobj.add(16)\nobj.median() # 17.0\nobj.median() # 17.0\nobj.median() # 17.0\nobj.median() # 17.0\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\nWhy it works:\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000223", "messages": [{"role": "user", "content": "**Sadeveden kertyminen**\n\n`heights[i]` on 1 leveän seinäosan korkeus. Sateen jälkeen vettä kertyy korkeampien osien väliin. Palauta kertyneen veden kokonaismäärä. Osia voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> trapped_water([5, 1, 5, 1])\n4\n>>> trapped_water([6, 4, 6, 4, 3, 6, 1, 3, 6])\n15\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "\n- Vesi kohdassa i = min(maksimi vasemmalla, maksimi oikealla) - heights[i], ei koskaan negatiivinen.\n- Molempien maksimien laskeminen joka i:lle on O(n²).\n- Juoksevat maksimit (tai kaksi osoitinta) antavat jokaisen tason lineaarisessa ajassa.\n- Reunatapaukset: tyhjä lista, alle 3 seinää, tasainen tai monotoninen profiili.\n- Vaativuus: O(n) aikaa, O(1) lisämuistia.\n\n\nKaksi osoitinta molemmista päistä: matalampi puoli määrää vedenpinnan, joten siirrä sitä sisään ja pidä kirjaa sen puolen korkeimmasta seinästä.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia."}], "meta": {"kind": "code.hard.water.trap0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000224", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('16620120116')\n6\n>>> decode_ways('1111220')\n8\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000225", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([6, 2, 6, 6, 4])\n4\n>>> rain_water([6, 0, 4, 3, 2, 0, 5, 4, 4])\n16\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\n**Complexity:** O(n) time, O(1) extra space.\n\nTests:\n```python\nassert rain_water([6, 2, 6, 6, 4]) == 4\nassert rain_water([6, 0, 4, 3, 2, 0, 5, 4, 4]) == 16\nassert rain_water([4, 2, 0, 3, 2, 5]) == 9\nassert rain_water([3, 0, 3]) == 3\nassert rain_water([]) == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000226", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(-3)\nobj.add(-14)\nobj.median() # -14\nobj.median() # -14\nobj.median() # -14\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000227", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(5, [[2, 4], [1, 0], [1, 2], [3, 4], [2, 4], [3, 2], [4, 1], [0, 4]])\nFalse\n>>> is_bipartite(4, [[0, 1]])\nTrue\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O((n + m) α(n)) time, O(n) space.\n\n\nUnion-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000228", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> max_container([3, 2])\n2\n>>> max_container([5, 2, 6, 4, 2, 5])\n25\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "Two pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Complexity:** O(n) time, O(1) extra space.\n\nTests:\n```python\nassert max_container([3, 2]) == 2\nassert max_container([5, 2, 6, 4, 2, 5]) == 25\nassert max_container([]) == 0\nassert max_container([1, 1]) == 1\nassert max_container([0, 0, 0]) == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000229", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('2101')\n1\n>>> decode_ways('12202612')\n8\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(n) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000230", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(2, [[1, 1], [0, 0], [1, 1], [1, 0], [1, 0], [0, 1]])\nFalse\n>>> is_bipartite(1, [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]])\nFalse\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O((n + m) α(n)) time, O(n) space.\n\n\nUnion-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000231", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> decode_ways('1260222')\n0\n>>> decode_ways('10261120')\n4\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\nMiksi tämä toimii:\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000232", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([2, 2, 3, 1, 3, 3, 3, 2, 5])\n3\n>>> rain_water([6, 5, 1, 2, 0, 2, 6])\n20\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\nWhy it works:\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000233", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([2, 4, 1, 3, 5, 0, 2, 4, 2, 2])\n10\n>>> rain_water([5, 2, 3, 5, 6, 2, 2, 1, 3])\n9\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000234", "messages": [{"role": "user", "content": "**Päiviä lämpimämpään päivään**\n\n`temps[i]` on päivän `i` lämpötila. Palauta jokaiselle päivälle, montako päivää pitää odottaa aidosti lämpimämpää päivää, tai 0, jos sellaista ei tule. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> steps_to_greater([0, 0])\n[0, 0]\n>>> steps_to_greater([8, 0, 2, 0])\n[0, 1, 0, 0]\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "steps_to_greater", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000235", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('22')\n2\n>>> decode_ways('600262611')\n0\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space.\n\nTests:\n```python\nassert decode_ways('22') == 2\nassert decode_ways('600262611') == 0\nassert decode_ways('226') == 3\nassert decode_ways('0') == 0\nassert decode_ways('10') == 1\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000236", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_larger_values([8, 0, 9, 3])\n[9, 9, -1, -1]\n>>> next_larger_values([7])\n[-1]\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert next_larger_values([8, 0, 9, 3]) == [9, 9, -1, -1]\nassert next_larger_values([7]) == [-1]\nassert next_larger_values([4, 3, 2, 1]) == [-1, -1, -1, -1]\nassert next_larger_values([7]) == [-1]\nassert next_larger_values([3, 3, 3]) == [-1, -1, -1]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_larger_values", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000237", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater([2, 9, 1, 1, 2, 0, 6, 2, 2, 9])\n[9, -1, 2, 2, 6, 6, 9, 9, 9, -1]\n>>> next_greater([7, 9, 1, 4, 6])\n[9, -1, 4, 6, -1]\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000238", "messages": [{"role": "user", "content": "**Päiviä lämpimämpään päivään**\n\n`temps[i]` on päivän `i` lämpötila. Palauta jokaiselle päivälle, montako päivää pitää odottaa aidosti lämpimämpää päivää, tai 0, jos sellaista ei tule. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> steps_to_greater([6, 0, 5, 4])\n[0, 1, 0, 0]\n>>> steps_to_greater([3, 9])\n[1, 0]\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\nMiksi tämä toimii:\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "steps_to_greater", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000239", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(4, [[0, 3], [2, 0], [3, 2], [2, 2], [2, 0], [2, 1]])\nFalse\n>>> can_split_in_two(6, [[1, 5], [4, 4]])\nFalse\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000240", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> count_decodings('22212121')\n34\n>>> count_decodings('0662')\n0\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "Dynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000241", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(6)\nobj.add(20)\nobj.median() # 6\nobj.median() # 6\nobj.median() # 6\nobj.median() # 6\nobj.add(2)\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Only the middle matters, so keep the two halves apart instead of a sorted list.\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n- Edge cases: one number, duplicates, negative numbers, even and odd counts.\n- Complexity: O(log n) per add, O(1) per median, O(n) space.\n\n\nTwo heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space.\n\nTests:\n```python\nobj = StreamMedian()\nobj.add(1)\nassert obj.median() == 1\nassert obj.median() == 1\nobj.add(-10)\nobj.add(-2)\nobj.add(19)\nassert obj.median() == -2\n\nobj = StreamMedian()\nobj.add(5)\nassert obj.median() == 5\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000242", "messages": [{"role": "user", "content": "**Sadeveden kertyminen**\n\n`heights[i]` on 1 leveän seinäosan korkeus. Sateen jälkeen vettä kertyy korkeampien osien väliin. Palauta kertyneen veden kokonaismäärä. Osia voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> trapped_water([2, 2, 4])\n0\n>>> trapped_water([4, 2, 2, 4, 6, 4, 4, 1, 2, 6])\n17\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "\n- Vesi kohdassa i = min(maksimi vasemmalla, maksimi oikealla) - heights[i], ei koskaan negatiivinen.\n- Molempien maksimien laskeminen joka i:lle on O(n²).\n- Juoksevat maksimit (tai kaksi osoitinta) antavat jokaisen tason lineaarisessa ajassa.\n- Reunatapaukset: tyhjä lista, alle 3 seinää, tasainen tai monotoninen profiili.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nRuudun yllä oleva vesi on min(korkein seinä vasemmalla, korkein seinä oikealla) miinus sen korkeus; laske molemmat juoksevat maksimit etukäteen.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\nMiksi tämä toimii:\n- Molempien maksimien laskeminen joka i:lle on O(n²).\n- Juoksevat maksimit (tai kaksi osoitinta) antavat jokaisen tason lineaarisessa ajassa.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.water.trap1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000243", "messages": [{"role": "user", "content": "**Päiviä lämpimämpään päivään**\n\n`temps[i]` on päivän `i` lämpötila. Palauta jokaiselle päivälle, montako päivää pitää odottaa aidosti lämpimämpää päivää, tai 0, jos sellaista ei tule. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> days_until_warmer([5, 9, 7, 4, 2, 3])\n[1, 0, 0, 0, 1, 0]\n>>> days_until_warmer([9, 3, 5, 3])\n[0, 1, 0, 0]\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\nMiksi tämä toimii:\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "days_until_warmer", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000244", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> trapped_water([5, 4, 3, 6, 0, 2, 3, 2, 6])\n20\n>>> trapped_water([2, 6, 4, 3])\n0\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "The water above a cell is min(highest wall to its left, highest wall to its right) minus its height; precompute both running maxima.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert trapped_water([5, 4, 3, 6, 0, 2, 3, 2, 6]) == 20\nassert trapped_water([2, 6, 4, 3]) == 0\nassert trapped_water([2, 0]) == 0\nassert trapped_water([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) == 6\nassert trapped_water([]) == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.water.trap1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000245", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_larger_values([5, 5, 4, 9, 1, 4, 0, 3, 2, 5])\n[9, 9, 9, -1, 4, 5, 3, 5, 5, -1]\n>>> next_larger_values([9, 6, 8, 9, 0, 6, 3, 5, 4])\n[-1, 8, 9, -1, 6, -1, 5, -1, -1]\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_larger_values(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_larger_values", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000246", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('626122220621')\n20\n>>> decode_ways('')\n1\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000247", "messages": [{"role": "user", "content": "**Sadeveden kertyminen**\n\n`heights[i]` on 1 leveän seinäosan korkeus. Sateen jälkeen vettä kertyy korkeampien osien väliin. Palauta kertyneen veden kokonaismäärä. Osia voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> trapped_water([1, 4, 2, 6, 3, 0, 2])\n4\n>>> trapped_water([2, 3, 1, 2, 3, 2, 3, 1])\n4\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "Ruudun yllä oleva vesi on min(korkein seinä vasemmalla, korkein seinä oikealla) miinus sen korkeus; laske molemmat juoksevat maksimit etukäteen.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\nMiksi tämä toimii:\n- Molempien maksimien laskeminen joka i:lle on O(n²).\n- Juoksevat maksimit (tai kaksi osoitinta) antavat jokaisen tason lineaarisessa ajassa.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.water.trap1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000248", "messages": [{"role": "user", "content": "**Eniten vettä vetävä astia**\n\n`heights[i]` on pystyviivan korkeus kohdassa x = i. Valitse kaksi viivaa, jotka x-akselin kanssa vetävät eniten vettä, ja palauta se määrä (lyhyempi viiva kertaa etäisyys). Viivoja voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> max_container([0, 6, 2, 0, 4, 6, 5, 0])\n25\n>>> max_container([2, 5, 1, 4, 0, 1, 4, 6])\n30\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "Kaksi osoitinta molemmista päistä; siirrä aina lyhyempää viivaa sisäänpäin, koska sen säilyttäminen voi antaa vain pienempiä astioita.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia."}], "meta": {"kind": "code.hard.water.container0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000249", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> is_bipartite(5, [[0, 0], [1, 4], [3, 3], [0, 1], [4, 4]])\nFalse\n>>> is_bipartite(4, [[0, 0], [0, 0], [3, 2], [0, 1], [1, 3], [1, 0]])\nFalse\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "Väritä jokainen komponentti kahdella värillä BFS:llä; naapuri, jolla on jo sama väri, todistaa jaon mahdottomaksi.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Vaativuus:** O(n + m) aikaa, O(n + m) muistia.\n\nTestit:\n```python\nassert not is_bipartite(5, [[0, 0], [1, 4], [3, 3], [0, 1], [4, 4]])\nassert not is_bipartite(4, [[0, 0], [0, 0], [3, 2], [0, 1], [1, 3], [1, 0]])\nassert not is_bipartite(1, [[0, 0]])\nassert is_bipartite(4, [[0, 1], [1, 2], [2, 3], [3, 0]])\nassert is_bipartite(5, [[0, 1], [2, 3]])\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000250", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(1, [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]])\nFalse\n>>> can_split_in_two(8, [[5, 5], [7, 3], [5, 6]])\nFalse\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "Two-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space.\n\nTests:\n```python\nassert not can_split_in_two(1, [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]])\nassert not can_split_in_two(8, [[5, 5], [7, 3], [5, 6]])\nassert can_split_in_two(5, [[0, 1], [2, 3]])\nassert not can_split_in_two(1, [[0, 0]])\nassert can_split_in_two(0, [])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000251", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `StreamMedian()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the lower of the two middle values. There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nExample:\n```python\nobj = StreamMedian()\nobj.add(-2)\nobj.add(-17)\nobj.add(17)\nobj.median() # -2\nobj.add(-11)\nobj.add(9)\nobj.median() # -2\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.low", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000252", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nExamples:\n```python\n>>> decode_ways('21')\n2\n>>> decode_ways('62611')\n4\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- Plain recursion repeats the same suffixes exponentially often; count per prefix instead.\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n- Edge cases: empty string, leading zero, '100', '27'.\n- Complexity: O(n) time, O(1) space.\n\n\nDynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\nWhy it works:\n- A single '0' is never a letter; two digits must be between 10 and 26.\n- Only the last two values are needed, so O(1) memory is possible.\n\n**Complexity:** O(n) time, O(1) space."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000253", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> is_bipartite(1, [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]])\nFalse\n>>> is_bipartite(7, [[6, 6], [4, 3], [1, 1], [1, 6], [1, 4]])\nFalse\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "Union-find solmuille ja niiden vastakkaisille puolille: kaari u-v yhdistää u:n ja ei-v:n sekä v:n ja ei-u:n; jos u ja v päätyvät samaan joukkoon, jako on mahdoton.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\nMiksi tämä toimii:\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n\n**Vaativuus:** O((n + m) α(n)) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000254", "messages": [{"role": "user", "content": "**Seuraava suurempi alkio**\n\nPalauta jokaiselle listan `nums` alkiolle ensimmäinen sen oikealla puolella oleva aidosti suurempi arvo, tai -1, jos sellaista ei ole. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> next_greater([9])\n[-1]\n>>> next_greater([4, 9, 6])\n[9, -1, -1]\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\nMiksi tämä toimii:\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000255", "messages": [{"role": "user", "content": "**Purkutapojen määrä**\n\nKirjaimet on koodattu numeroiksi: A = 1, B = 2, ..., Z = 26. Annettu numerojono `s`; palauta, kuinka monella tavalla sen voi purkaa takaisin kirjaimiksi, modulo 1 000 000 007. Koodissa ei ole koskaan etunollaa (\"06\" ei kelpaa), ja tyhjällä jonolla on täsmälleen yksi purku. `s` voi olla satojatuhansia numeroita pitkä.\n\nAllekirjoitus:\n```python\ndef decode_ways(s: str) -> int:\n```\n\nEsimerkit:\n```python\n>>> decode_ways('21222612')\n26\n>>> decode_ways('')\n1\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "\n- Pelkkä rekursio toistaa samoja loppuosia eksponentiaalisesti; laske etuliitteittäin.\n- Yksittäinen '0' ei ole koskaan kirjain; kahden numeron on oltava välillä 10–26.\n- Vain kaksi viimeistä arvoa tarvitaan, joten O(1)-muisti riittää.\n- Reunatapaukset: tyhjä jono, etunolla, '100', '27'.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nDynaaminen ohjelmointi etuliitteiden yli: viimeinen kirjain käyttää joko yhden numeron (ei '0') tai kaksi numeroa (10..26), joten ways[i] = ways[i - 1] + ways[i - 2], kun ne kelpaavat.\n\n```python\ndef decode_ways(s: str) -> int:\n MOD = 1_000_000_007\n ways = [0] * (len(s) + 1)\n ways[0] = 1 # the empty prefix has one decoding\n for i in range(1, len(s) + 1):\n if s[i - 1] != \"0\":\n ways[i] = ways[i - 1] # last letter uses one digit\n if i >= 2 and \"10\" <= s[i - 2:i] <= \"26\":\n ways[i] = (ways[i] + ways[i - 2]) % MOD # last letter uses two digits\n return ways[len(s)]\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia.\n\nTestit:\n```python\nassert decode_ways('21222612') == 26\nassert decode_ways('') == 1\nassert decode_ways('27') == 1\nassert decode_ways('0') == 0\nassert decode_ways('226') == 3\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.decode_ways.count0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "decode_ways", "problem_id": "4de4667536f7", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000256", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `StreamMedian()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahden keskimmäisen arvon keskiarvo (liukuluku, esim. 2.5). Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nEsimerkki:\n```python\nobj = StreamMedian()\nobj.add(-15)\nobj.add(-10)\nobj.add(-3)\nobj.median() # -10\nobj.median() # -10\nobj.add(-15)\nobj.add(9)\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "Kaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000257", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([2, 4, 6, 2, 0, 1, 0, 1, 0])\n2\n>>> rain_water([])\n0\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "Two pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000258", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater_circular([8, 5, 3, 1, 0, 7, 3, 7])\n[-1, 7, 7, 7, 7, 8, 7, 8]\n>>> next_greater_circular([3, 4])\n[4, -1]\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert next_greater_circular([8, 5, 3, 1, 0, 7, 3, 7]) == [-1, 7, 7, 7, 7, 8, 7, 8]\nassert next_greater_circular([3, 4]) == [4, -1]\nassert next_greater_circular([4, 3, 2, 1]) == [-1, 4, 4, 4]\nassert next_greater_circular([2, 1, 2, 4, 3]) == [4, 2, 4, -1, 4]\nassert next_greater_circular([7]) == [-1]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000259", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater([5, 9, 7, 1, 4, 9, 6, 3])\n[9, -1, 9, 4, 9, -1, -1, -1]\n>>> next_greater([4])\n[-1]\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000260", "messages": [{"role": "user", "content": "**Running median**\n\nImplement `MedianTracker()` with `add(x)`, which adds an integer, and `median()`, which returns the median of all numbers added so far (at least one). For an even count the median is the mean of the two middle values (a float, e.g. 2.5). There can be 200,000 operations, so sorting on every call is too slow.\n\nSignature:\n```python\nclass MedianTracker:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> float: ...\n```\n\nExample:\n```python\nobj = MedianTracker()\nobj.add(5)\nobj.add(-8)\nobj.median() # -1.5\nobj.add(13)\nobj.add(3)\nobj.median() # 4.0\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "Two heaps: a max-heap for the smaller half and a min-heap for the larger half, kept balanced so the median is always at the top of one or both.\n\n```python\nimport heapq\n\n\nclass MedianTracker:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> float:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return (-self.low[0] + self.high[0]) / 2\n```\n\nWhy it works:\n- Push into the low half, move its largest to the high half, and rebalance so low has the extra item.\n- Python's heapq is a min-heap: store negated values for the max-heap.\n\n**Complexity:** O(log n) per add, O(1) per median, O(n) space."}], "meta": {"kind": "code.hard.running_median.avg", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "MedianTracker", "problem_id": "0f0f2aecf2f8", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000261", "messages": [{"role": "user", "content": "**Days until a warmer day**\n\n`temps[i]` is the temperature on day `i`. For each day, return how many days you have to wait for a strictly warmer day, or 0 if no warmer day comes. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> steps_to_greater([7])\n[0]\n>>> steps_to_greater([9])\n[0]\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert steps_to_greater([7]) == [0]\nassert steps_to_greater([9]) == [0]\nassert steps_to_greater([]) == []\nassert steps_to_greater([3, 3, 3]) == [0, 0, 0]\nassert steps_to_greater([2, 1, 2, 4, 3]) == [3, 1, 1, 0, 0]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "steps_to_greater", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000262", "messages": [{"role": "user", "content": "**Juokseva mediaani**\n\nToteuta `StreamMedian()`, jossa `add(x)` lisää kokonaisluvun ja `median()` palauttaa kaikkien tähän asti lisättyjen lukujen mediaanin (lukuja on ainakin yksi). Parillisella määrällä mediaani on kahdesta keskimmäisestä arvosta pienempi. Operaatioita voi olla 200 000, joten lajittelu joka kutsulla on liian hidasta.\n\nAllekirjoitus:\n```python\nclass StreamMedian:\n def __init__(self): ...\n def add(self, x: int) -> None: ...\n def median(self) -> int: ...\n```\n\nEsimerkki:\n```python\nobj = StreamMedian()\nobj.add(-2)\nobj.median() # -2\nobj.median() # -2\nobj.median() # -2\nobj.add(-10)\nobj.median() # -10\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "Kaksi kekoa: maksimikeko pienemmälle puoliskolle ja minimikeko suuremmalle, tasapainossa niin, että mediaani on aina toisen tai molempien huipulla.\n\n```python\nimport heapq\n\n\nclass StreamMedian:\n def __init__(self):\n self.low = [] # max-heap (negated) with the smaller half\n self.high = [] # min-heap with the larger half\n\n def add(self, x: int) -> None:\n heapq.heappush(self.low, -x)\n heapq.heappush(self.high, -heapq.heappop(self.low)) # move the largest of the low half up\n if len(self.high) > len(self.low):\n heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra element\n\n def median(self) -> int:\n if len(self.low) > len(self.high):\n return -self.low[0]\n return -self.low[0]\n```\n\nMiksi tämä toimii:\n- Lisää alempaan puoliskoon, siirrä sen suurin ylempään ja tasapainota niin, että alemmassa on ylimääräinen.\n- Pythonin heapq on minimikeko: tallenna maksimikekoon negatiiviset arvot.\n\n**Vaativuus:** O(log n) per add, O(1) per median, O(n) muistia."}], "meta": {"kind": "code.hard.running_median.low", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 3, "entry": "StreamMedian", "problem_id": "bced3b12e0dd", "complexity": "O(log n) per add, O(1) per median, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 17 inputs; large input under 4 s"}} {"id": "codehard-test-000263", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater_circular([4, 9, 5, 1, 7])\n[9, -1, 7, 7, 9]\n>>> next_greater_circular([5])\n[-1]\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef next_greater_circular(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\nWhy it works:\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater_circular", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000264", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(3, [[0, 2], [0, 1]])\nTrue\n>>> can_split_in_two(5, [[2, 4], [1, 3], [4, 0], [4, 1]])\nTrue\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space.\n\nTests:\n```python\nassert can_split_in_two(3, [[0, 2], [0, 1]])\nassert can_split_in_two(5, [[2, 4], [1, 3], [4, 0], [4, 1]])\nassert can_split_in_two(1, [])\nassert can_split_in_two(0, [])\nassert can_split_in_two(4, [[0, 1], [1, 2], [2, 3], [3, 0]])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000265", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> circular_next_larger([9, 4, 6, 2, 4, 3, 7, 1, 2])\n[-1, 6, 7, 4, 7, 7, 9, 2, 9]\n>>> circular_next_larger([7])\n[-1]\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "circular_next_larger", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000266", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef trapped_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> trapped_water([2, 2, 4, 6, 6])\n0\n>>> trapped_water([6, 6, 1, 0, 3, 4, 6, 5, 4, 6])\n19\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Two pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef trapped_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "trapped_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000267", "messages": [{"role": "user", "content": "**Decode ways**\n\nLetters are encoded as numbers: A = 1, B = 2, ..., Z = 26. Given a string of digits `s`, return how many ways it can be decoded back into letters, modulo 1,000,000,007. A code never has a leading zero (\"06\" is not valid), and the empty string has exactly one decoding. `s` can be hundreds of thousands of digits long.\n\nSignature:\n```python\ndef count_decodings(s: str) -> int:\n```\n\nExamples:\n```python\n>>> count_decodings('6112201021')\n6\n>>> count_decodings('10')\n1\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "Dynamic programming over prefixes: the last letter uses either one digit (not '0') or two digits (10..26), so ways[i] = ways[i - 1] + ways[i - 2] when those are valid.\n\n```python\ndef count_decodings(s: str) -> int:\n MOD = 1_000_000_007\n prev, cur = 0, 1 # ways for the prefixes ending two and one positions back\n for i, ch in enumerate(s):\n nxt = cur if ch != \"0\" else 0\n if i >= 1 and \"10\" <= s[i - 1:i + 1] <= \"26\":\n nxt = (nxt + prev) % MOD\n prev, cur = cur, nxt\n return cur\n```\n\n**Complexity:** O(n) time, O(1) space.\n\nTests:\n```python\nassert count_decodings('6112201021') == 6\nassert count_decodings('10') == 1\nassert count_decodings('10') == 1\nassert count_decodings('0') == 0\nassert count_decodings('100') == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.decode_ways.count1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "count_decodings", "problem_id": "ffb4ed307420", "complexity": "O(n) time, O(1) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000268", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(4, [[0, 2], [1, 3], [3, 1], [1, 1], [2, 0]])\nFalse\n>>> can_split_in_two(8, [[2, 1], [6, 4], [7, 5], [7, 5], [6, 7], [3, 2], [4, 2], [6, 3]])\nTrue\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space.\n\nTests:\n```python\nassert not can_split_in_two(4, [[0, 2], [1, 3], [3, 1], [1, 1], [2, 0]])\nassert can_split_in_two(8, [[2, 1], [6, 4], [7, 5], [7, 5], [6, 7], [3, 2], [4, 2], [6, 3]])\nassert can_split_in_two(0, [])\nassert not can_split_in_two(3, [[0, 1], [1, 2], [2, 0]])\nassert not can_split_in_two(1, [[0, 0]])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000269", "messages": [{"role": "user", "content": "**Seuraava suurempi alkio**\n\nPalauta jokaiselle listan `nums` alkiolle ensimmäinen sen oikealla puolella oleva aidosti suurempi arvo, tai -1, jos sellaista ei ole. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> next_greater([7, 3, 4, 4, 9, 8, 6, 9])\n[9, 4, 9, 9, -1, 9, 9, -1]\n>>> next_greater([4, 0, 9, 0, 0, 8, 5])\n[9, 9, -1, 8, 8, -1, -1]\n```\n\nToteuta se Pythonilla."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000270", "messages": [{"role": "user", "content": "**Next greater element**\n\nFor each element of `nums`, return the first value to its right that is strictly greater, or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> next_greater([5, 0, 6, 7, 6, 8, 4, 9, 1])\n[6, 6, 7, 8, 8, 9, 9, -1, -1]\n>>> next_greater([4, 1, 8, 2, 7])\n[8, 8, -1, 7, -1]\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef next_greater(nums: list[int]) -> list[int]:\n out = [-1] * len(nums)\n stack = [] # indices still waiting for a greater value\n for i, x in enumerate(nums):\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.next_greater.value", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "next_greater", "problem_id": "fc7d664e1dcd", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000271", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> is_bipartite(3, [[2, 0], [2, 2], [1, 0], [2, 0]])\nFalse\n>>> is_bipartite(8, [[3, 6], [2, 5], [4, 0], [1, 1], [5, 0], [2, 2]])\nFalse\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "Union-find solmuille ja niiden vastakkaisille puolille: kaari u-v yhdistää u:n ja ei-v:n sekä v:n ja ei-u:n; jos u ja v päätyvät samaan joukkoon, jako on mahdoton.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\nMiksi tämä toimii:\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n\n**Vaativuus:** O((n + m) α(n)) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000272", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(7, [[3, 1], [3, 2], [0, 4], [5, 3]])\nTrue\n>>> is_bipartite(3, [[0, 0], [1, 1], [2, 0]])\nFalse\n```\n\nGive an efficient Python solution and briefly explain the idea."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\nWhy it works:\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000273", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> max_container([])\n0\n>>> max_container([0, 6, 3, 5, 5, 1])\n15\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "Two pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Complexity:** O(n) time, O(1) extra space.\n\nTests:\n```python\nassert max_container([]) == 0\nassert max_container([0, 6, 3, 5, 5, 1]) == 15\nassert max_container([1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49\nassert max_container([4, 3, 2, 1, 4]) == 16\nassert max_container([0, 0, 0]) == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000274", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([4])\n0\n>>> rain_water([4, 6, 6, 2, 4, 4, 1, 3, 4, 0])\n6\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends: the lower side decides the water level there, so move it inward while tracking the highest wall seen on that side.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n left_max = right_max = water = 0\n while left < right:\n if heights[left] < heights[right]: # the left side is the limiting wall\n left_max = max(left_max, heights[left])\n water += left_max - heights[left]\n left += 1\n else:\n right_max = max(right_max, heights[right])\n water += right_max - heights[right]\n right -= 1\n return water\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.trap0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "9ba3271d1364", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000275", "messages": [{"role": "user", "content": "**Eniten vettä vetävä astia**\n\n`heights[i]` on pystyviivan korkeus kohdassa x = i. Valitse kaksi viivaa, jotka x-akselin kanssa vetävät eniten vettä, ja palauta se määrä (lyhyempi viiva kertaa etäisyys). Viivoja voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> max_container([4])\n0\n>>> max_container([6, 0, 3, 1, 1, 0, 5, 0, 0])\n30\n```\n\nToteuta se Pythonilla."}, {"role": "assistant", "content": "Kaksi osoitinta molemmista päistä; siirrä aina lyhyempää viivaa sisäänpäin, koska sen säilyttäminen voi antaa vain pienempiä astioita.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia."}], "meta": {"kind": "code.hard.water.container0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000276", "messages": [{"role": "user", "content": "**Seuraava suurempi alkio kehällä**\n\n`nums` on kehämäinen: viimeisen alkion jälkeen tulee taas ensimmäinen. Palauta jokaiselle alkiolle ensimmäinen aidosti suurempi arvo eteenpäin kulkien (kehän ympäri), tai -1, jos sellaista ei ole. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> circular_next_larger([3, 9, 1, 2, 7])\n[9, -1, 2, 7, 9]\n>>> circular_next_larger([9, 0, 4, 5, 4, 6, 3, 5])\n[-1, 4, 5, 6, 6, 9, 5, 9]\n```\n\nRatkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus."}, {"role": "assistant", "content": "\n- Jokaisen myöhemmän alkion tarkistaminen on O(n²); jokainen alkio tarvitsee ratkaista vain kerran.\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n- Reunatapaukset: tyhjä lista, yksi alkio, kaikki yhtä suuria, aidosti laskeva.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nMonotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle. Kaksi kierrosta taulukon yli hoitaa kehän.\n\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\nMiksi tämä toimii:\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "circular_next_larger", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000277", "messages": [{"role": "user", "content": "**Seuraava suurempi alkio kehällä**\n\n`nums` on kehämäinen: viimeisen alkion jälkeen tulee taas ensimmäinen. Palauta jokaiselle alkiolle ensimmäinen aidosti suurempi arvo eteenpäin kulkien (kehän ympäri), tai -1, jos sellaista ei ole. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> circular_next_larger([5])\n[-1]\n>>> circular_next_larger([7, 3])\n[-1, 7]\n```\n\nKirjoita ratkaisu Pythonilla ja lisää muutama testi."}, {"role": "assistant", "content": "Monotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle. Kaksi kierrosta taulukon yli hoitaa kehän.\n\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia.\n\nTestit:\n```python\nassert circular_next_larger([5]) == [-1]\nassert circular_next_larger([7, 3]) == [-1, 7]\nassert circular_next_larger([4, 3, 2, 1]) == [-1, 4, 4, 4]\nassert circular_next_larger([2, 1, 2, 4, 3]) == [4, 2, 4, -1, 4]\nassert circular_next_larger([7]) == [-1]\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "circular_next_larger", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000278", "messages": [{"role": "user", "content": "**Päiviä lämpimämpään päivään**\n\n`temps[i]` on päivän `i` lämpötila. Palauta jokaiselle päivälle, montako päivää pitää odottaa aidosti lämpimämpää päivää, tai 0, jos sellaista ei tule. Listassa voi olla satoja tuhansia alkioita.\n\nAllekirjoitus:\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n```\n\nEsimerkit:\n```python\n>>> steps_to_greater([2, 6, 7, 7])\n[1, 1, 0, 0]\n>>> steps_to_greater([7, 9, 4, 9, 2, 9, 4])\n[1, 0, 1, 0, 1, 0, 0]\n```\n\nToteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset."}, {"role": "assistant", "content": "\n- Jokaisen myöhemmän alkion tarkistaminen on O(n²); jokainen alkio tarvitsee ratkaista vain kerran.\n- Pinon arvot ovat ei-kasvavia, joten uusi arvo ratkaisee jonon pinon päältä.\n- Aidosti suurempi: yhtä suuret arvot eivät ratkaise toisiaan.\n- Reunatapaukset: tyhjä lista, yksi alkio, kaikki yhtä suuria, aidosti laskeva.\n- Vaativuus: O(n) aikaa, O(n) muistia.\n\n\nMonotoninen pino odottavista indekseistä: kun suurempi arvo saapuu, se on vastaus jokaiselle pinon päällä olevalle pienemmälle arvolle.\n\n```python\ndef steps_to_greater(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia.\n\nTestit:\n```python\nassert steps_to_greater([2, 6, 7, 7]) == [1, 1, 0, 0]\nassert steps_to_greater([7, 9, 4, 9, 2, 9, 4]) == [1, 0, 1, 0, 1, 0, 0]\nassert steps_to_greater([4, 3, 2, 1]) == [0, 0, 0, 0]\nassert steps_to_greater([2, 1, 2, 4, 3]) == [3, 1, 1, 0, 0]\nassert steps_to_greater([]) == []\n```\nKaikki nämä assertit menevät läpi yllä olevalla ratkaisulla."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "steps_to_greater", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000279", "messages": [{"role": "user", "content": "**Eniten vettä vetävä astia**\n\n`heights[i]` on pystyviivan korkeus kohdassa x = i. Valitse kaksi viivaa, jotka x-akselin kanssa vetävät eniten vettä, ja palauta se määrä (lyhyempi viiva kertaa etäisyys). Viivoja voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> max_container([0, 1, 3, 2, 6, 3, 5, 0, 1, 6])\n30\n>>> max_container([4, 2, 6, 0, 4, 2, 5, 0, 0])\n24\n```\n\nAnna tehokas Python-ratkaisu ja selitä idea lyhyesti."}, {"role": "assistant", "content": "\n- Kaikkien parien tarkistaminen on O(n²).\n- Kun lyhyempi viiva on kiinnitetty, jokainen kapeampi astia on huonompi, joten pudota se viiva.\n- Jokainen askel poistaa yhden viivan: lineaarinen aika.\n- Reunatapaukset: alle 2 viivaa, yhtä korkeat viivat, nollat.\n- Vaativuus: O(n) aikaa, O(1) lisämuistia.\n\n\nKaksi osoitinta molemmista päistä; siirrä aina lyhyempää viivaa sisäänpäin, koska sen säilyttäminen voi antaa vain pienempiä astioita.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\nMiksi tämä toimii:\n- Kun lyhyempi viiva on kiinnitetty, jokainen kapeampi astia on huonompi, joten pudota se viiva.\n- Jokainen askel poistaa yhden viivan: lineaarinen aika.\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia."}], "meta": {"kind": "code.hard.water.container0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000280", "messages": [{"role": "user", "content": "**Sadeveden kertyminen**\n\n`heights[i]` on 1 leveän seinäosan korkeus. Sateen jälkeen vettä kertyy korkeampien osien väliin. Palauta kertyneen veden kokonaismäärä. Osia voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> rain_water([2, 5, 1, 3, 1])\n2\n>>> rain_water([0, 0, 2, 5, 1, 1])\n0\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "Ruudun yllä oleva vesi on min(korkein seinä vasemmalla, korkein seinä oikealla) miinus sen korkeus; laske molemmat juoksevat maksimit etukäteen.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Vaativuus:** O(n) aikaa, O(n) muistia."}], "meta": {"kind": "code.hard.water.trap1", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000281", "messages": [{"role": "user", "content": "**Next greater element in a circle**\n\n`nums` is circular: after the last element comes the first one again. For each element, return the first strictly greater value found by walking forward (wrapping around), or -1 if there is none. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> circular_next_larger([5, 5, 5, 7, 9, 9, 9, 0])\n[7, 7, 7, 9, -1, -1, -1, 5]\n>>> circular_next_larger([1, 0, 8, 4, 3, 4, 1])\n[8, 8, -1, 8, 4, 8, 8]\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "A monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack. Two passes over the array handle the wrap-around.\n\n```python\ndef circular_next_larger(nums: list[int]) -> list[int]:\n n = len(nums)\n out = [-1] * n\n stack = []\n for i in range(2 * n): # two passes simulate wrapping around\n x = nums[i % n]\n while stack and nums[stack[-1]] < x:\n out[stack.pop()] = x\n if i < n:\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert circular_next_larger([5, 5, 5, 7, 9, 9, 9, 0]) == [7, 7, 7, 9, -1, -1, -1, 5]\nassert circular_next_larger([1, 0, 8, 4, 3, 4, 1]) == [8, 8, -1, 8, 4, 8, 8]\nassert circular_next_larger([7]) == [-1]\nassert circular_next_larger([1, 2, 3, 4]) == [2, 3, 4, -1]\nassert circular_next_larger([3, 3, 3]) == [-1, -1, -1]\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.circular", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "circular_next_larger", "problem_id": "0e2235b7a25a", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000282", "messages": [{"role": "user", "content": "**Jaa verkko kahteen puoleen**\n\nSolmuja on `n` (0..n-1) ja suuntaamattomat kaaret `[u, v]`. Palauta True, jos solmut voi jakaa kahteen ryhmään niin, että jokainen kaari yhdistää eri ryhmien solmuja, ja muuten False (silmukka tekee sen mahdottomaksi). Solmuja ja kaaria voi olla 200 000.\n\nAllekirjoitus:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nEsimerkit:\n```python\n>>> is_bipartite(4, [[2, 1], [3, 1]])\nTrue\n>>> is_bipartite(8, [[1, 1], [0, 5]])\nFalse\n```\n\nRatkaise tämä Pythonilla."}, {"role": "assistant", "content": "\n- Verkon voi jakaa kahtia täsmälleen silloin, kun siinä ei ole paritonta sykliä.\n- Komponentit ovat riippumattomia: aloita uusi väritys jokaisesta värittämättömästä solmusta.\n- Yksikin ristiriita riittää palauttamaan False.\n- Reunatapaukset: ei solmuja, erilliset solmut, silmukka, pariton tai parillinen sykli.\n- Vaativuus: O(n + m) aikaa, O(n + m) muistia.\n\n\nVäritä jokainen komponentti kahdella värillä BFS:llä; naapuri, jolla on jo sama väri, todistaa jaon mahdottomaksi.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Vaativuus:** O(n + m) aikaa, O(n + m) muistia."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000283", "messages": [{"role": "user", "content": "**Days until a warmer day**\n\n`temps[i]` is the temperature on day `i`. For each day, return how many days you have to wait for a strictly warmer day, or 0 if no warmer day comes. The list can have hundreds of thousands of elements.\n\nSignature:\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n```\n\nExamples:\n```python\n>>> days_until_warmer([7])\n[0]\n>>> days_until_warmer([7, 6])\n[0, 0]\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Checking every later element is O(n²); each element only needs to be resolved once.\n- Values on the stack are non-increasing, so a new value resolves a run from the top.\n- Strictly greater: equal values do not resolve each other.\n- Edge cases: empty list, one element, all equal, strictly decreasing.\n- Complexity: O(n) time, O(n) space.\n\n\nA monotonic stack of indices that are still waiting: when a greater value arrives, it is the answer for every smaller value on top of the stack.\n\n```python\ndef days_until_warmer(temps: list[int]) -> list[int]:\n out = [0] * len(temps)\n stack = [] # indices of days without a warmer day yet\n for i, t in enumerate(temps):\n while stack and temps[stack[-1]] < t:\n j = stack.pop()\n out[j] = i - j\n stack.append(i)\n return out\n```\n\n**Complexity:** O(n) time, O(n) space.\n\nTests:\n```python\nassert days_until_warmer([7]) == [0]\nassert days_until_warmer([7, 6]) == [0, 0]\nassert days_until_warmer([1, 2, 3, 4]) == [1, 1, 1, 0]\nassert days_until_warmer([2, 1, 2, 4, 3]) == [3, 1, 1, 0, 0]\nassert days_until_warmer([]) == []\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.next_greater.wait", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "days_until_warmer", "problem_id": "8f953ff42b1f", "complexity": "O(n) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000284", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(2, [[1, 0], [1, 0], [0, 1], [1, 0], [1, 1]])\nFalse\n>>> is_bipartite(2, [[1, 0], [1, 1], [0, 1], [1, 1], [1, 0], [0, 0], [0, 1]])\nFalse\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000285", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([2, 6, 6, 0])\n0\n>>> rain_water([1, 5, 4, 2, 2])\n0\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- Water at i = min(max to the left, max to the right) - heights[i], never negative.\n- Recomputing both maxima for every i is O(n²).\n- Running maxima (or two pointers) give every level in linear time.\n- Edge cases: empty list, fewer than 3 walls, a flat or monotonic profile.\n- Complexity: O(n) time, O(n) space.\n\n\nThe water above a cell is min(highest wall to its left, highest wall to its right) minus its height; precompute both running maxima.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.water.trap1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000286", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(8, [[4, 0], [2, 7], [0, 6], [6, 6], [0, 7], [0, 7]])\nFalse\n>>> can_split_in_two(6, [[2, 1]])\nTrue\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "Two-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\nWhy it works:\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000287", "messages": [{"role": "user", "content": "**Trapping rain water**\n\n`heights[i]` is the height of a 1-wide wall segment. After rain, water collects between higher segments. Return the total amount of water trapped. There can be hundreds of thousands of segments.\n\nSignature:\n```python\ndef rain_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> rain_water([3, 5, 4, 0, 5, 2, 6, 6, 5, 2])\n9\n>>> rain_water([3, 1, 3, 6, 3, 2, 2, 4, 3, 2])\n7\n```\n\nImplement it in Python."}, {"role": "assistant", "content": "The water above a cell is min(highest wall to its left, highest wall to its right) minus its height; precompute both running maxima.\n\n```python\ndef rain_water(heights: list[int]) -> int:\n n = len(heights)\n if n == 0:\n return 0\n left_max, right_max = [0] * n, [0] * n\n left_max[0] = heights[0]\n for i in range(1, n):\n left_max[i] = max(left_max[i - 1], heights[i])\n right_max[-1] = heights[-1]\n for i in range(n - 2, -1, -1):\n right_max[i] = max(right_max[i + 1], heights[i])\n return sum(min(left_max[i], right_max[i]) - heights[i] for i in range(n))\n```\n\n**Complexity:** O(n) time, O(n) space."}], "meta": {"kind": "code.hard.water.trap1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "rain_water", "problem_id": "313d51069f9b", "complexity": "O(n) time, O(n) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 21 inputs; large input under 4 s"}} {"id": "codehard-test-000288", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> max_container([5, 2, 3])\n6\n>>> max_container([0, 4, 3, 0, 1, 1, 2, 5])\n24\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- Checking all pairs is O(n²).\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n- Edge cases: fewer than 2 lines, equal heights, zeros.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Complexity:** O(n) time, O(1) extra space."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000289", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(5, [[3, 0], [3, 4], [3, 4], [1, 0], [2, 2], [2, 4]])\nFalse\n>>> is_bipartite(8, [[7, 6], [6, 7], [6, 7], [3, 2], [1, 6]])\nTrue\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000290", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(8, [[2, 4]])\nTrue\n>>> is_bipartite(5, [])\nTrue\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\nWhy it works:\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000291", "messages": [{"role": "user", "content": "**Eniten vettä vetävä astia**\n\n`heights[i]` on pystyviivan korkeus kohdassa x = i. Valitse kaksi viivaa, jotka x-akselin kanssa vetävät eniten vettä, ja palauta se määrä (lyhyempi viiva kertaa etäisyys). Viivoja voi olla satoja tuhansia.\n\nAllekirjoitus:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nEsimerkit:\n```python\n>>> most_water([6, 1, 4])\n8\n>>> most_water([5, 3, 0, 0, 2, 1])\n8\n```\n\nKirjoita ratkaisu Pythonilla."}, {"role": "assistant", "content": "\n- Kaikkien parien tarkistaminen on O(n²).\n- Kun lyhyempi viiva on kiinnitetty, jokainen kapeampi astia on huonompi, joten pudota se viiva.\n- Jokainen askel poistaa yhden viivan: lineaarinen aika.\n- Reunatapaukset: alle 2 viivaa, yhtä korkeat viivat, nollat.\n- Vaativuus: O(n) aikaa, O(1) lisämuistia.\n\n\nKaksi osoitinta molemmista päistä; siirrä aina lyhyempää viivaa sisäänpäin, koska sen säilyttäminen voi antaa vain pienempiä astioita.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Vaativuus:** O(n) aikaa, O(1) lisämuistia."}], "meta": {"kind": "code.hard.water.container0", "lang": "fi", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000292", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(7, [[5, 4]])\nTrue\n>>> is_bipartite(2, [[0, 1], [0, 1], [0, 0], [0, 0], [1, 0]])\nFalse\n```\n\nSolve it in Python and explain your approach and its complexity."}, {"role": "assistant", "content": "Union-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\nWhy it works:\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n\n**Complexity:** O((n + m) α(n)) time, O(n) space."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "explain", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000293", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(7, [[6, 3], [5, 2], [5, 1]])\nTrue\n>>> is_bipartite(8, [[2, 4], [4, 4], [1, 7], [0, 7], [2, 5]])\nFalse\n```\n\nSolve this in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000294", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef max_container(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> max_container([])\n0\n>>> max_container([])\n0\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- Checking all pairs is O(n²).\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n- Edge cases: fewer than 2 lines, equal heights, zeros.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef max_container(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Complexity:** O(n) time, O(1) extra space.\n\nTests:\n```python\nassert max_container([]) == 0\nassert max_container([]) == 0\nassert max_container([1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49\nassert max_container([5]) == 0\nassert max_container([]) == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "max_container", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000295", "messages": [{"role": "user", "content": "**Container with the most water**\n\n`heights[i]` is the height of a vertical line at x = i. Pick two lines that, together with the x-axis, hold the most water, and return that amount (the shorter line times the distance). There can be hundreds of thousands of lines.\n\nSignature:\n```python\ndef most_water(heights: list[int]) -> int:\n```\n\nExamples:\n```python\n>>> most_water([1, 1, 6, 5, 6, 6, 0, 5, 5, 4])\n30\n>>> most_water([2, 4, 1, 3, 3, 5, 5])\n20\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "\n- Checking all pairs is O(n²).\n- With the shorter line fixed, every narrower container is no better, so drop that line.\n- Each step removes one line: linear time.\n- Edge cases: fewer than 2 lines, equal heights, zeros.\n- Complexity: O(n) time, O(1) extra space.\n\n\nTwo pointers from both ends; always move the shorter line inward, since keeping it can only give smaller containers.\n\n```python\ndef most_water(heights: list[int]) -> int:\n left, right = 0, len(heights) - 1\n best = 0\n while left < right:\n best = max(best, min(heights[left], heights[right]) * (right - left))\n if heights[left] < heights[right]: # moving the taller side can never help\n left += 1\n else:\n right -= 1\n return best\n```\n\n**Complexity:** O(n) time, O(1) extra space.\n\nTests:\n```python\nassert most_water([1, 1, 6, 5, 6, 6, 0, 5, 5, 4]) == 30\nassert most_water([2, 4, 1, 3, 3, 5, 5]) == 20\nassert most_water([4, 3, 2, 1, 4]) == 16\nassert most_water([]) == 0\nassert most_water([5]) == 0\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.water.container0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "most_water", "problem_id": "30207b590d58", "complexity": "O(n) time, O(1) extra space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000296", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(8, [[1, 4], [6, 0], [0, 5], [4, 5], [6, 0], [2, 0], [1, 2]])\nFalse\n>>> can_split_in_two(8, [[6, 1], [5, 0]])\nTrue\n```\n\nImplement it in Python, then add assert-based tests that cover the edge cases."}, {"role": "assistant", "content": "Two-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space.\n\nTests:\n```python\nassert not can_split_in_two(8, [[1, 4], [6, 0], [0, 5], [4, 5], [6, 0], [2, 0], [1, 2]])\nassert can_split_in_two(8, [[6, 1], [5, 0]])\nassert can_split_in_two(0, [])\nassert not can_split_in_two(3, [[0, 1], [1, 2], [2, 0]])\nassert can_split_in_two(1, [])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000297", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(8, [[6, 2], [2, 5], [3, 4], [1, 0], [0, 0], [4, 1], [3, 3]])\nFalse\n>>> is_bipartite(6, [[1, 1]])\nFalse\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}} {"id": "codehard-test-000298", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> is_bipartite(4, [[2, 0], [1, 1], [3, 0], [2, 1], [3, 2], [3, 2], [1, 0], [1, 1]])\nFalse\n>>> is_bipartite(4, [[2, 2], [3, 3], [1, 3]])\nFalse\n```\n\nWrite the solution in Python and include a few tests."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O((n + m) α(n)) time, O(n) space.\n\n\nUnion-find over each node and its opposite side: an edge u-v joins u with not-v and v with not-u; if u and v ever end up together, it is impossible.\n\n```python\ndef is_bipartite(n: int, edges: list[list[int]]) -> bool:\n parent = list(range(2 * n)) # node x and its \"opposite side\" x + n\n\n def find(x):\n while parent[x] != x:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n\n for u, v in edges:\n if find(u) == find(v):\n return False # u and v were forced onto the same side\n parent[find(u)] = find(v + n) # u goes with the opposite of v\n parent[find(v)] = find(u + n)\n return True\n```\n\n**Complexity:** O((n + m) α(n)) time, O(n) space.\n\nTests:\n```python\nassert not is_bipartite(4, [[2, 0], [1, 1], [3, 0], [2, 1], [3, 2], [3, 2], [1, 0], [1, 1]])\nassert not is_bipartite(4, [[2, 2], [3, 3], [1, 3]])\nassert is_bipartite(0, [])\nassert is_bipartite(4, [[0, 1], [1, 2], [2, 3], [3, 0]])\nassert is_bipartite(5, [[0, 1], [2, 3]])\n```\nAll of these assertions pass against the solution above."}], "meta": {"kind": "code.hard.bipartite.check1", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "is_bipartite", "problem_id": "2c6e8329069d", "complexity": "O((n + m) α(n)) time, O(n) space", "mode": "tests", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s; tests run"}} {"id": "codehard-test-000299", "messages": [{"role": "user", "content": "**Split a graph into two sides**\n\nThere are `n` nodes (0..n-1) and undirected edges `[u, v]`. Return True if the nodes can be split into two groups so that every edge joins nodes from different groups, and False otherwise (a self-loop makes it impossible). There can be 200,000 nodes and edges.\n\nSignature:\n```python\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n```\n\nExamples:\n```python\n>>> can_split_in_two(1, [[0, 0], [0, 0], [0, 0], [0, 0]])\nFalse\n>>> can_split_in_two(6, [[1, 4], [3, 2], [2, 3], [3, 3], [2, 3], [0, 3]])\nFalse\n```\n\nWrite the solution in Python."}, {"role": "assistant", "content": "\n- A graph splits in two exactly when it has no odd cycle.\n- Each component is independent: start a new colouring for every uncoloured node.\n- One conflict anywhere is enough to return False.\n- Edge cases: no nodes, isolated nodes, a self-loop, an odd or even cycle.\n- Complexity: O(n + m) time, O(n + m) space.\n\n\nTwo-colour every component with BFS; a neighbour that already has the same colour proves it is impossible.\n\n```python\nfrom collections import deque\n\n\ndef can_split_in_two(n: int, edges: list[list[int]]) -> bool:\n adj = [[] for _ in range(n)]\n for u, v in edges:\n adj[u].append(v)\n adj[v].append(u)\n color = [-1] * n\n for s in range(n):\n if color[s] != -1:\n continue\n color[s] = 0\n queue = deque([s])\n while queue: # BFS: neighbours must get the other colour\n u = queue.popleft()\n for v in adj[u]:\n if color[v] == -1:\n color[v] = 1 - color[u]\n queue.append(v)\n elif color[v] == color[u]:\n return False\n return True\n```\n\n**Complexity:** O(n + m) time, O(n + m) space."}], "meta": {"kind": "code.hard.bipartite.check0", "lang": "en", "generator": "kreatix-code-hard", "version": "0.1.0", "difficulty": 2, "entry": "can_split_in_two", "problem_id": "cba29f356cb6", "complexity": "O(n + m) time, O(n + m) space", "mode": "solve", "checked_by": "reference == brute-force oracle on 20 inputs; large input under 4 s"}}