# Samples 24 random examples from the train split, shown in full. ## code.hard.top_k_words.alpha_ties (en) **user** ```text **Top k words** Return the `k` most frequent words in `words`, most frequent first. Words with the same count are ordered alphabetically. If there are fewer than `k` distinct words, return all of them. Signature: ```python def top_k_words(words: list[str], k: int) -> list[str]: ``` Examples: ```python >>> top_k_words(['alder', 'elm', 'pine', 'oak', 'pine', 'ash', 'elm', 'pine', 'elm', 'rowan', 'ash', 'pine', 'fir'], 5) ['pine', 'elm', 'ash', 'alder', 'fir'] >>> top_k_words(['oak', 'elm', 'oak', 'oak', 'pine', 'oak', 'ash', 'ash'], 1) ['oak'] ``` Write the solution in Python. ``` **assistant** ```text - Count every word. - The ranking key (-count, word) handles both the order and the alphabetical tie-break. - Only k results are needed, so a heap avoids sorting everything. - Edge cases: empty list, k larger than the number of distinct words, ties. - Complexity: O(n + m log k) time, O(m) space. Count with Counter, then rank by (-count, word); heapq.nsmallest keeps it O(m log k) for m distinct words. ```python from collections import Counter def top_k_words(words: list[str], k: int) -> list[str]: counts = Counter(words) ranked = sorted(counts, key=lambda w: (-counts[w], w)) return ranked[:k] ``` **Complexity:** O(n + m log k) time, O(m) space. ``` ## code.hard.word_break.fewest (en) **user** ```text **Fewest words** Return the smallest number of words from `words` that concatenate to exactly `s` (each word can be used any number of times), or -1 if it is impossible. The empty string needs 0 words. `s` can be tens of thousands of characters long. Signature: ```python def fewest_words(s: str, words: list[str]) -> int: ``` Examples: ```python >>> fewest_words('cba', ['c', 'a', 'ca', 'bca', 'abca', 'ba']) 2 >>> fewest_words('cabcac', ['c', 'abca', 'a', 'bc']) 3 ``` Give an efficient Python solution and briefly explain the idea. ``` **assistant** ```text - Trying every split recursively is exponential; each prefix only needs to be solved once. - Put the words in a set and only try lengths up to the longest word. - Take the minimum over words ending at i, plus one. - Edge cases: empty string, empty word list, overlapping words. - Complexity: O(n · L) set lookups (L = longest word length), O(n) space. Dynamic programming over prefixes: best[i] describes s[:i], and it is built from best[i - k] for every word length k whose last k characters form a word. ```python def fewest_words(s: str, words: list[str]) -> int: INF = float("inf") vocab = set(words) longest = max(map(len, vocab), default=0) n = len(s) best = [INF] * (n + 1) best[0] = 0 # the empty prefix for i in range(1, n + 1): for k in range(1, min(longest, i) + 1): # only word lengths that exist need checking w = s[i - k:i] if w in vocab: best[i] = min(best[i], best[i - len(w)] + 1) return best[n] if best[n] < INF else -1 ``` Why it works: - Put the words in a set and only try lengths up to the longest word. - Take the minimum over words ending at i, plus one. **Complexity:** O(n · L) set lookups (L = longest word length), O(n) space. ``` ## code.hard.common_sequence.subseq (fi) **user** ```text **Pisin yhteinen alijono** Palauta merkkijonojen `a` ja `b` pisimmän yhteisen alijonon pituus (merkit samassa järjestyksessä, ei välttämättä vierekkäin). Molemmat jonot voivat olla yli tuhat merkkiä pitkiä. Allekirjoitus: ```python def lcs_length(a: str, b: str) -> int: ``` Esimerkit: ```python >>> lcs_length('acaabb', 'bbbababa') 3 >>> lcs_length('ccaaabb', 'aacbbcac') 4 ``` Ratkaise tämä Pythonilla. ``` **assistant** ```text - Kaikkien alijonojen läpikäynti on eksponentiaalista; taulukko etuliiteparien yli on O(n·m). - dp[i][j] = dp[i-1][j-1] + 1 täsmätessä, muuten max(dp[i-1][j], dp[i][j-1]). - Jokainen rivi riippuu vain edellisestä, joten O(m)-muisti riittää. - Reunatapaukset: tyhjä jono, identtiset jonot, ei yhteisiä merkkejä. - Vaativuus: O(len(a) · len(b)) aikaa, O(len(b)) muistia. Dynaaminen ohjelmointi molempien jonojen etuliitteiden yli, vain edellinen rivi muistissa: täsmäävät merkit jatkavat diagonaalia, muuten valitaan parempi kahdesta yhden merkin pudotuksesta. ```python def lcs_length(a: str, b: str) -> int: prev = [0] * (len(b) + 1) # row for the previous prefix of a for ca in a: cur = [0] * (len(b) + 1) for j, cb in enumerate(b, 1): cur[j] = prev[j - 1] + 1 if ca == cb else max(prev[j], cur[j - 1]) prev = cur return prev[-1] ``` **Vaativuus:** O(len(a) · len(b)) aikaa, O(len(b)) muistia. ``` ## code.hard.prefix_counter.class0 (en) **user** ```text **Prefix counter** Implement `PrefixCounter()` with three methods: `insert(word)` adds a word (duplicates count again), `count(word)` returns how many times exactly `word` was inserted, and `starts_with(prefix)` returns how many inserted words start with `prefix` (every word starts with the empty prefix). There can be 100,000 operations, so scanning all words per query is too slow. Signature: ```python class PrefixCounter: def __init__(self): ... def insert(self, word: str) -> None: ... def count(self, word: str) -> int: ... def starts_with(self, prefix: str) -> int: ... ``` Example: ```python obj = PrefixCounter() obj.starts_with('aacc') # 0 obj.starts_with('') # 0 obj.starts_with('bb') # 0 ``` Implement it in Python. ``` **assistant** ```text A trie of nested dicts that stores, at every node, how many words pass through it and how many end there; each operation walks one path. ```python class PrefixCounter: def __init__(self): self.root = {} # nested dicts; "#" holds counts at each node def insert(self, word: str) -> None: node = self.root node["#"] = node.get("#", 0) + 1 for ch in word: node = node.setdefault(ch, {}) node["#"] = node.get("#", 0) + 1 # words passing through this prefix node["$"] = node.get("$", 0) + 1 # words ending exactly here def _walk(self, text): node = self.root for ch in text: node = node.get(ch) if node is None: return None return node def count(self, word: str) -> int: node = self._walk(word) return node.get("$", 0) if node else 0 def starts_with(self, prefix: str) -> int: node = self._walk(prefix) return node.get("#", 0) if node else 0 ``` **Complexity:** O(len(word)) per operation, O(total length) space. ``` ## code.hard.longest_window.kdistinct (fi) **user** ```text **Pisin osajono, jossa on enintään k eri merkkiä** Palauta merkkijonon `s` pisimmän sellaisen osajonon pituus, jossa on enintään `k` eri merkkiä (`k >= 0`). `s` voi olla satojatuhansia merkkejä pitkä. Allekirjoitus: ```python def longest_k_distinct(s: str, k: int) -> int: ``` Esimerkit: ```python >>> longest_k_distinct('dbbabbbdca', 0) 0 >>> longest_k_distinct('dbdadc', 1) 1 ``` Ratkaise tämä Pythonilla. ``` **assistant** ```text Liukuva ikkuna ja laskuri sen merkeistä: laajenna oikealle, ja niin kauan kuin eri merkkejä on yli `k`, poista merkkejä vasemmalta. ```python from collections import Counter def longest_k_distinct(s: str, k: int) -> int: counts = Counter() best = start = 0 for i, ch in enumerate(s): counts[ch] += 1 while len(counts) > k: # too many kinds: shrink from the left left = s[start] counts[left] -= 1 if counts[left] == 0: del counts[left] start += 1 best = max(best, i - start + 1) return best ``` **Vaativuus:** O(n) aikaa, O(k) muistia. ``` ## code.hard.count_islands.4 (en) **user** ```text **Count islands** The grid is a list of equal-length strings of '1' (land) and '0' (water). Two land cells belong to the same island when they are next to each other horizontally or vertically. Return the number of islands. Signature: ```python def islands(grid: list[str]) -> int: ``` Examples: ```python >>> islands(['011110', '111000', '100010', '110000', '101100', '010111']) 4 >>> islands(['110', '000', '100', '000']) 2 ``` Write the solution in Python. ``` **assistant** ```text Scan the grid; every unvisited land cell starts a new island, which an iterative flood fill (explicit stack, no recursion limit) marks as visited. ```python def islands(grid: list[str]) -> int: if not grid: return 0 rows, cols = len(grid), len(grid[0]) seen = [[False] * cols for _ in range(rows)] steps = [(1, 0), (-1, 0), (0, 1), (0, -1)] islands = 0 for r in range(rows): for c in range(cols): if grid[r][c] != "1" or seen[r][c]: continue islands += 1 seen[r][c] = True stack = [(r, c)] while stack: y, x = stack.pop() for dy, dx in steps: ny, nx = y + dy, x + dx if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == "1" and not seen[ny][nx]: seen[ny][nx] = True stack.append((ny, nx)) return islands ``` **Complexity:** O(rows · cols) time and space. ``` ## code.hard.stock_profit.fee (fi) **user** ```text **Osakekauppa välityspalkkiolla** `prices[i]` on osakkeen hinta päivänä `i`. Saat tehdä kauppoja niin monta kuin haluat, mutta voit omistaa enintään yhden osakkeen kerrallaan, ja jokainen myynti maksaa `fee`. Palauta suurin mahdollinen voitto. Päiviä voi olla satoja tuhansia. Allekirjoitus: ```python def trade_with_fee(prices: list[int], fee: int) -> int: ``` Esimerkit: ```python >>> trade_with_fee([5, 4, 8, 8, 2, 9, 1], 1) 9 >>> trade_with_fee([8, 1], 3) 0 ``` Anna tehokas Python-ratkaisu ja selitä idea lyhyesti. ``` **assistant** ```text - Ahneet säännöt eivät toimi palkkioiden kanssa; pidä kirjaa parhaasta voitosta jokaisessa tilassa. - cash = paras ilman osaketta, hold = paras osakkeen kanssa; myynti tuottaa p - fee. - Päivitä kaikki tilat edellisen päivän arvoista kerralla (monikkosijoitus). - Reunatapaukset: tyhjä lista, yksi päivä, pelkästään laskevat hinnat. - Vaativuus: O(n) aikaa, O(1) muistia. Dynaaminen ohjelmointi päivien yli, yksi tila kutakin tilannetta kohden (osake hallussa tai ei), päivitetään yhdessä joka päivä. ```python def trade_with_fee(prices: list[int], fee: int) -> int: cash, hold = 0, float("-inf") # best profit without / with a share in hand for p in prices: cash, hold = max(cash, hold + p - fee), max(hold, cash - p) return cash ``` Miksi tämä toimii: - cash = paras ilman osaketta, hold = paras osakkeen kanssa; myynti tuottaa p - fee. - Päivitä kaikki tilat edellisen päivän arvoista kerralla (monikkosijoitus). **Vaativuus:** O(n) aikaa, O(1) muistia. ``` ## code.hard.time_map.class (fi) **user** ```text **Versioitu avain-arvovarasto** Toteuta `VersionedStore()`, jossa on `set(key, value, timestamp)` ja `get(key, timestamp)`. get palauttaa avaimelle `key` asetetun arvon suurimmalla aikaleimalla, joka on <= `timestamp`, tai tyhjän merkkijonon, jos sellaista ei ole. Kullekin avaimelle set kutsutaan aidosti kasvavin aikaleimoin. get:n on oltava nopeampi kuin historian läpikäynti. Allekirjoitus: ```python class VersionedStore: def set(self, key: str, value: str, timestamp: int) -> None: ... def get(self, key: str, timestamp: int) -> str: ... ``` Esimerkki: ```python obj = VersionedStore() obj.set('k1', 'v35', 3) obj.get('k2', 2) # '' obj.set('k1', 'v25', 5) obj.set('k1', 'v48', 6) obj.get('k0', 0) # '' obj.get('k0', 0) # '' obj.get('k1', 5) # 'v25' ``` Toteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset. ``` **assistant** ```text Kullekin avaimelle aikaleimat tulevat järjestyksessä, joten lisää ne listaan ja vastaa get-kutsuun bisect_right-funktiolla ajassa O(log n). ```python from bisect import bisect_right from collections import defaultdict class VersionedStore: def __init__(self): self.times = defaultdict(list) self.values = defaultdict(list) def set(self, key: str, value: str, timestamp: int) -> None: # timestamps for one key arrive in increasing order self.times[key].append(timestamp) self.values[key].append(value) def get(self, key: str, timestamp: int) -> str: i = bisect_right(self.times[key], timestamp) return self.values[key][i - 1] if i else "" ``` **Vaativuus:** set O(1), get O(log n). Testit: ```python obj = VersionedStore() obj.set('k1', 'v25', 5) assert obj.get('k0', 0) == '' assert obj.get('k2', 2) == '' obj.set('k2', 'v18', 4) assert obj.get('k0', 1) == '' obj.set('k0', 'v22', 2) obj.set('k2', 'v3', 6) obj.set('k0', 'v86', 7) assert obj.get('k2', 3) == '' assert obj.get('k0', 9) == 'v86' obj = VersionedStore() assert obj.get('a', 5) == '' ``` Kaikki nämä assertit menevät läpi yllä olevalla ratkaisulla. ``` ## code.hard.union_find.components (en) **user** ```text **Count connected groups** There are `n` nodes numbered 0..n-1 and a list of undirected edges `[u, v]`. Return the number of connected groups. `n` and the number of edges can both be 200,000. Signature: ```python def number_of_groups(n: int, edges: list[list[int]]) -> int: ``` Examples: ```python >>> number_of_groups(2, [[1, 1], [0, 1], [0, 1], [0, 0], [1, 0]]) 1 >>> number_of_groups(2, [[0, 0], [1, 1], [0, 0], [0, 1], [1, 0], [1, 1]]) 1 ``` Implement it in Python, then add assert-based tests that cover the edge cases. ``` **assistant** ```text - Keep a parent pointer per node; find() follows it to the group's root. - Union by size and path halving keep every find almost O(1). - Every successful union merges two groups, so the count drops by one. - Edge cases: no nodes, no edges, self-loops, repeated edges. - Complexity: O((n + m) α(n)) time, O(n) space. Union-find (disjoint sets) with path halving and union by size: each edge is processed in nearly constant time. ```python def number_of_groups(n: int, edges: list[list[int]]) -> int: parent = list(range(n)) size = [1] * n def find(x): while parent[x] != x: parent[x] = parent[parent[x]] # path halving x = parent[x] return x groups = n for u, v in edges: ru, rv = find(u), find(v) if ru != rv: if size[ru] < size[rv]: ru, rv = rv, ru parent[rv] = ru # union by size keeps the trees shallow size[ru] += size[rv] groups -= 1 return groups ``` **Complexity:** O((n + m) α(n)) time, O(n) space. Tests: ```python assert number_of_groups(2, [[1, 1], [0, 1], [0, 1], [0, 0], [1, 0]]) == 1 assert number_of_groups(2, [[0, 0], [1, 1], [0, 0], [0, 1], [1, 0], [1, 1]]) == 1 assert number_of_groups(4, [[0, 1], [2, 3]]) == 2 assert number_of_groups(1, []) == 1 assert number_of_groups(1, [[0, 0]]) == 1 ``` All of these assertions pass against the solution above. ``` ## code.hard.search_answer.ship (fi) **user** ```text **Pienin laivan kapasiteetti** Paketit painoilla `weights` on kuljetettava annetussa järjestyksessä `days` päivässä (1 <= days <= len(weights)). Joka päivä laiva ottaa peräkkäisiä paketteja, joiden yhteispaino ei ylitä sen kapasiteettia. Palauta pienin kapasiteetti, jolla tämä onnistuu. Paketteja voi olla 300 000. Allekirjoitus: ```python def smallest_capacity(weights: list[int], days: int) -> int: ``` Esimerkit: ```python >>> smallest_capacity([6, 5, 9, 3, 1, 9, 6, 6], 6) 11 >>> smallest_capacity([9, 8, 7, 1, 3, 1, 8, 6, 5], 1) 48 ``` Anna tehokas Python-ratkaisu ja selitä idea lyhyesti. ``` **assistant** ```text Binäärihaku vastauksen yli: suurempi kapasiteetti ei koskaan tarvitse enempää päiviä, joten testaa ehdokas lineaarisella ahneella tarkistuksella ja puolita väli välillä max(weights) (painavimman paketin on mahduttava) ja sum(weights) (yksi päivä). ```python def smallest_capacity(weights: list[int], days: int) -> int: def fits(cap): # greedy: fill each day as much as possible used, load = 1, 0 for w in weights: if load + w > cap: used, load = used + 1, 0 load += w return used <= days lo, hi = max(weights), sum(weights) while lo < hi: # smallest value for which fits() is True mid = (lo + hi) // 2 if fits(mid): hi = mid else: lo = mid + 1 return lo ``` Miksi tämä toimii: - Tarkistus on monotoninen (suurempi kapasiteetti ei koskaan tarvitse enempää päiviä), mikä tekee binäärihausta pätevän. - Etsi ensimmäinen arvo, jolla tarkistus menee läpi (lo < hi, onnistuessa hi = mid). **Vaativuus:** O(n log R) aikaa (R = size of the answer range), O(1) muistia. ``` ## code.hard.meeting_rooms.rooms (fi) **user** ```text **Kokoushuoneiden vähimmäismäärä** Jokainen kokous on `[start, end)`: se varaa huoneen hetkestä `start` hetkeen `end` asti, mutta ei hetkeä `end`. Palauta pienin määrä huoneita, jotta kaksi kokousta ei ole samaan aikaan samassa huoneessa. Kello 10 päättyvä kokous vapauttaa huoneen kello 10 alkavalle. Allekirjoitus: ```python def min_meeting_rooms(meetings: list[list[int]]) -> int: ``` Esimerkit: ```python >>> min_meeting_rooms([[1, 9], [9, 19], [10, 13], [1, 2], [8, 9], [15, 23]]) 2 >>> min_meeting_rooms([[3, 7], [13, 15]]) 1 ``` Toteuta se Pythonilla. ``` **assistant** ```text - Jokainen alku lisää yhden käynnissä olevan kokouksen ja jokainen loppu poistaa yhden. - Järjestä tapahtumat ajan mukaan; samalla hetkellä loppu (-1) ennen alkua (+1), koska välit ovat puoliavoimia. - Pidä kirjaa käynnissä olevista ja niiden maksimista. - Reunatapaukset: tyhjä lista, identtiset kokoukset, peräkkäiset kokoukset. - Vaativuus: O(n log n) aikaa, O(n) muistia. Muuta kokoukset +1/-1-tapahtumiksi ja käy ne aikajärjestyksessä läpi niin, että samalla hetkellä päättymiset käsitellään ennen alkamisia; käynnissä olevien määrän maksimi on vastaus. ```python def min_meeting_rooms(meetings: list[list[int]]) -> int: events = [] for start, end in meetings: events.append((start, 1)) events.append((end, -1)) events.sort() # at equal times -1 sorts first: a room frees before it is reused running = best = 0 for _, delta in events: running += delta best = max(best, running) return best ``` **Vaativuus:** O(n log n) aikaa, O(n) muistia. ``` ## code.hard.window_extreme.max0 (en) **user** ```text **Sliding window maximum** Given a list `nums` and a window size `k` (1 <= k <= len(nums)), return the largest value in every window of `k` consecutive elements, from left to right. The list can have hundreds of thousands of elements and `k` can be large, so recomputing each window is too slow. Signature: ```python def sliding_max(nums: list[int], k: int) -> list[int]: ``` Examples: ```python >>> sliding_max([2], 1) [2] >>> sliding_max([-9, 2, 5, -5, 3, 9, 1, 5, -7, -5, -2, 9], 6) [9, 9, 9, 9, 9, 9, 9] ``` Solve it in Python and explain your approach and its complexity. ``` **assistant** ```text - Recomputing each window costs O(n·k); keep candidates between windows instead. - An element that is older and no better than a newer one can never be the answer again. - The window covers indices i - k + 1 .. i; anything at index <= i - k has left it. - Edge cases: k == 1, k == len(nums), equal values, a single element. - Complexity: O(n) time, O(k) extra space. A monotonic deque of indices: drop indices from the back while their value can no longer win, drop the front when it leaves the window; the front is always the answer. ```python from collections import deque def sliding_max(nums: list[int], k: int) -> list[int]: window = deque() # indices; their values are monotonic from front to back out = [] for i, x in enumerate(nums): while window and nums[window[-1]] <= x: window.pop() # can never be the answer again: x is newer and at least as good window.append(i) if window[0] <= i - k: window.popleft() # the front index has left the window if i >= k - 1: out.append(nums[window[0]]) return out ``` Why it works: - An element that is older and no better than a newer one can never be the answer again. - The window covers indices i - k + 1 .. i; anything at index <= i - k has left it. **Complexity:** O(n) time, O(k) extra space. ``` ## code.hard.histogram.rect0 (en) **user** ```text **Largest rectangle in a histogram** `heights[i]` is the height of bar `i` in a histogram; every bar is 1 wide and bars stand side by side. Return the area of the largest axis-aligned rectangle that fits inside the bars. There can be hundreds of thousands of bars. Signature: ```python def max_histogram_area(heights: list[int]) -> int: ``` Examples: ```python >>> max_histogram_area([0, 1, 6, 5, 3, 0, 8, 3, 0, 6]) 10 >>> max_histogram_area([3, 7, 5]) 10 ``` Solve it in Python and explain your approach and its complexity. ``` **assistant** ```text - The best shape is limited by its lowest bar, so try every bar as the lowest one. - A monotonic stack gives the nearest lower bar on both sides in one pass. - Area = height × width. - Edge cases: empty list, zero heights, all bars equal, strictly increasing or decreasing. - Complexity: O(n) time, O(n) space. For each bar, find how far it can extend left and right while it stays the lowest bar, using a monotonic stack; the best shape that uses this bar as its lowest one is then known. ```python def max_histogram_area(heights: list[int]) -> int: stack = [] # indices of bars with increasing heights best = 0 for i, h in enumerate(heights + [0]): # the 0 sentinel flushes the stack at the end while stack and heights[stack[-1]] >= h: height = heights[stack.pop()] left = stack[-1] + 1 if stack else 0 width = i - left best = max(best, height * width) stack.append(i) return best ``` Why it works: - A monotonic stack gives the nearest lower bar on both sides in one pass. - Area = height × width. **Complexity:** O(n) time, O(n) space. ``` ## code.hard.edit_distance.i3d3s2 (fi) **user** ```text **Painotettu muokkausetäisyys** Muuta merkkijono `a` merkkijonoksi `b`. Merkin lisääminen maksaa 3, poistaminen 3 ja merkin korvaaminen eri merkillä 2. Palauta pienin kokonaiskustannus. Allekirjoitus: ```python def transform_cost(a: str, b: str) -> int: ``` Esimerkit: ```python >>> transform_cost('caacab', 'cbdca') 7 >>> transform_cost('bdbcda', 'ddabd') 9 ``` Ratkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus. ``` **assistant** ```text - dp[i][j] = kustannus muuttaa a[:i] merkkijonoksi b[:j]. - Siirtymät: poista a[i-1], lisää b[j-1] tai säilytä/korvaa viimeiset merkit. - Ensimmäinen rivi ja sarake ovat pelkkiä lisäyksiä ja poistoja. - Vain edellinen rivi tarvitaan: O(len(b)) muistia. - Vaativuus: O(len(a) · len(b)) aikaa, O(len(b)) muistia. Klassinen muokkausetäisyyden DP kolmella kustannuksella, säilyttäen vain edellisen rivin. Koska korvaus maksaa 2, se voi olla parempi kuin poisto ja lisäys. ```python def transform_cost(a: str, b: str) -> int: INS, DEL, SUB = 3, 3, 2 prev = [j * INS for j in range(len(b) + 1)] for i in range(1, len(a) + 1): cur = [i * DEL] + [0] * len(b) for j in range(1, len(b) + 1): keep = prev[j - 1] + (0 if a[i - 1] == b[j - 1] else SUB) cur[j] = min(keep, prev[j] + DEL, cur[j - 1] + INS) prev = cur return prev[len(b)] ``` Miksi tämä toimii: - Siirtymät: poista a[i-1], lisää b[j-1] tai säilytä/korvaa viimeiset merkit. - Ensimmäinen rivi ja sarake ovat pelkkiä lisäyksiä ja poistoja. **Vaativuus:** O(len(a) · len(b)) aikaa, O(len(b)) muistia. ``` ## code.hard.subarray_count.sum_k (fi) **user** ```text **Laske osataulukot** Palauta, montako sellaista listan `nums` epätyhjää yhtenäistä osataulukkoa on, joiden summa on tasan `k`. Arvot voivat olla negatiivisia, ja listassa voi olla satoja tuhansia alkioita. Allekirjoitus: ```python def count_sum_k(nums: list[int], k: int) -> int: ``` Esimerkit: ```python >>> count_sum_k([-2, 2, 0], 0) 3 >>> count_sum_k([-2, -5], 2) 0 ``` Kirjoita ratkaisu Pythonilla ja lisää muutama testi. ``` **assistant** ```text - Negatiiviset arvot estävät liukuvan ikkunan; etuliitesummat toimivat kaikilla arvoilla. - Aloita tyhjällä etuliitteellä kerran laskettuna, jotta indeksistä 0 alkavat osataulukot mukana. - Hae ennen kuin lisäät nykyisen etuliitteen, jotta osataulukko ei ole koskaan tyhjä. - Reunatapaukset: tyhjä lista, nollat, negatiiviset luvut, k == 0. - Vaativuus: O(n) aikaa, O(n) muistia. Etuliitesummat: osataulukon (i, j] summa on k täsmälleen, kun prefix[j] - prefix[i] == k, joten laske hajautustaulusta aiemmat etuliitteet, jotka ovat prefix - k. ```python from collections import defaultdict def count_sum_k(nums: list[int], k: int) -> int: seen = defaultdict(int) seen[0] = 1 # the empty prefix total = prefix = 0 for x in nums: prefix += x total += seen[prefix - k] # earlier prefixes p with prefix - p == k seen[prefix] += 1 return total ``` **Vaativuus:** O(n) aikaa, O(n) muistia. Testit: ```python assert count_sum_k([-2, 2, 0], 0) == 3 assert count_sum_k([-2, -5], 2) == 0 assert count_sum_k([0, 0, 0], 3) == 0 assert count_sum_k([1, -1, 1, -1], 2) == 0 assert count_sum_k([0, 0, 0], 0) == 6 ``` Kaikki nämä assertit menevät läpi yllä olevalla ratkaisulla. ``` ## code.hard.expr_eval.shunting (en) **user** ```text **Evaluate an arithmetic expression** The string contains non-negative integers, `+`, `-`, `*`, `/`, parentheses, spaces, and unary minus (as in `-3` or `-(2 + 1)`). Evaluate it with the usual precedence (`*` and `/` before `+` and `-`, left to right within a level). `/` is integer division that truncates toward zero (so `7 / -2` is -3). Do not use `eval`. Inputs never divide by zero. Signature: ```python def evaluate(expr: str) -> int: ``` Examples: ```python >>> evaluate('-17 / 17') -1 >>> evaluate('-18 + 2') -16 ``` Write the solution in Python and include a few tests. ``` **assistant** ```text The shunting-yard algorithm with two stacks; unary minus becomes its own highest-precedence, right-associative operator. ```python def evaluate(expr: str) -> int: def div(a, b): # integer division that truncates toward zero q = abs(a) // abs(b) return q if (a >= 0) == (b > 0) else -q prec = {"+": 1, "-": 1, "*": 2, "/": 2, "~": 3} nums, ops = [], [] def apply(): op = ops.pop() if op == "~": nums.append(-nums.pop()) return b, a = nums.pop(), nums.pop() nums.append(a + b if op == "+" else a - b if op == "-" else a * b if op == "*" else div(a, b)) i, expect_value = 0, True while i < len(expr): ch = expr[i] if ch == " ": i += 1 continue if ch.isdigit(): j = i while j < len(expr) and expr[j].isdigit(): j += 1 nums.append(int(expr[i:j])) i, expect_value = j, False continue if ch == "(": ops.append(ch) elif ch == ")": while ops[-1] != "(": apply() ops.pop() expect_value = False i += 1 continue else: op = "~" if (ch == "-" and expect_value) else ch while ops and ops[-1] != "(" and op != "~" and prec[ops[-1]] >= prec[op]: apply() ops.append(op) expect_value = True i += 1 continue i += 1 while ops: apply() return nums[0] ``` **Complexity:** O(n) time and space. Tests: ```python assert evaluate('-17 / 17') == -1 assert evaluate('-18 + 2') == -16 assert evaluate('7') == 7 assert evaluate('(1)') == 1 assert evaluate('2 - 3 - 4') == -5 ``` All of these assertions pass against the solution above. ``` ## code.hard.coin_change.ways (en) **user** ```text **Coin combinations** Given distinct positive coin values (unlimited supply of each) and an amount, return the number of different combinations that add up to the amount, modulo 1,000,000,007. Order does not matter: 1+2 and 2+1 are the same combination. Signature: ```python def coin_combinations(coins: list[int], amount: int) -> int: ``` Examples: ```python >>> coin_combinations([10], 5) 0 >>> coin_combinations([8], 7) 0 ``` Solve it in Python and explain your approach and its complexity. ``` **assistant** ```text - Greedy is wrong for general coin sets; use DP over amounts 0..amount. - min: best[a] = min over coins of best[a - c] + 1; ways: ways[a] += ways[a - c]. - For ways, loop order matters: coins outside counts combinations, not ordered sequences. - Edge cases: amount 0, impossible amounts, a single coin. - Complexity: O(len(coins) · amount) time, O(amount) space. Count with coins in the outer loop and amounts in the inner loop, so each combination is built in one fixed coin order and counted once. ```python def coin_combinations(coins: list[int], amount: int) -> int: MOD = 1_000_000_007 ways = [1] + [0] * amount for c in coins: # coins outer: each combination counted once, order ignored for a in range(c, amount + 1): ways[a] = (ways[a] + ways[a - c]) % MOD return ways[amount] ``` Why it works: - min: best[a] = min over coins of best[a - c] + 1; ways: ways[a] += ways[a - c]. - For ways, loop order matters: coins outside counts combinations, not ordered sequences. **Complexity:** O(len(coins) · amount) time, O(amount) space. ``` ## code.hard.range_sum.class0 (en) **user** ```text **Range sums with updates** Implement `RangeSum(nums)` with `update(index, value)`, which sets `nums[index] = value`, and `query(left, right)`, which returns the sum of `nums[left..right]` (both ends included, `left <= right`). There can be 100,000 values and 150,000 operations, so summing the range for every query is too slow. Signature: ```python class RangeSum: def __init__(self, nums: list[int]): ... def update(self, index: int, value: int) -> None: ... def query(self, left: int, right: int) -> int: ... ``` Example: ```python obj = RangeSum([6, -2, 4, 5, 4, -8, -5, 9]) obj.update(1, 9) obj.query(5, 6) # -13 obj.query(1, 5) # 14 obj.update(6, -1) obj.query(1, 6) # 13 obj.query(2, 6) # 4 obj.update(0, -8) ``` Implement it in Python. ``` **assistant** ```text - A plain list makes queries O(n); prefix sums make updates O(n). A tree balances both. - Store the current values too: update(index, value) adds value - old. - Both operations are O(log n). - Edge cases: one value, a range of length 1, updating to the same value, negative numbers. - Complexity: O(n) to build, O(log n) per operation, O(n) space. A Fenwick (binary indexed) tree: an update adds the difference along O(log n) nodes, and a range sum is the difference of two prefix sums. ```python class RangeSum: def __init__(self, nums: list[int]): self.n = len(nums) self.vals = list(nums) self.tree = [0] * (self.n + 1) # Fenwick tree, 1-based for i, x in enumerate(nums): self._add(i + 1, x) def _add(self, i, delta): while i <= self.n: self.tree[i] += delta i += i & -i def _prefix(self, i): # sum of the first i values total = 0 while i > 0: total += self.tree[i] i -= i & -i return total def update(self, index: int, value: int) -> None: self._add(index + 1, value - self.vals[index]) self.vals[index] = value def query(self, left: int, right: int) -> int: return self._prefix(right + 1) - self._prefix(left) ``` **Complexity:** O(n) to build, O(log n) per operation, O(n) space. ``` ## code.hard.spiral.cw (fi) **user** ```text **Spiraalijärjestys** Palauta `rows × cols` -matriisin kaikki alkiot spiraalijärjestyksessä alkaen vasemmasta yläkulmasta ja kulkien myötäpäivään (ensin oikealle ylintä riviä) keskustaan asti. Allekirjoitus: ```python def spiral(matrix: list[list[int]]) -> list[int]: ``` Esimerkit: ```python >>> spiral([[7, 5, 6, 4], [5, 5, 9, 9], [4, 5, 6, 8], [5, 1, 8, 0]]) [7, 5, 6, 4, 9, 8, 0, 8, 1, 5, 4, 5, 5, 9, 6, 5] >>> spiral([[0, 9, 6, 0, 3], [5, 9, 3, 8, 8], [1, 1, 6, 0, 0], [7, 3, 8, 2, 6]]) [0, 9, 6, 0, 3, 8, 0, 6, 2, 8, 3, 7, 1, 5, 9, 3, 8, 0, 6, 1] ``` Ratkaise Pythonilla ja selitä lähestymistapa ja aikavaativuus. ``` **assistant** ```text - Pidä ylä-, ala-, vasen ja oikea raja ja kavenna niitä jokaisen kerroksen jälkeen. - Lue neljä sivua vaaditussa suunnassa. - Suojaa kolmas ja neljäs sivu, jotta yksittäistä riviä tai saraketta ei lueta kahdesti. - Reunatapaukset: tyhjä matriisi, yksi rivi, yksi sarake, ei-neliön muotoiset. - Vaativuus: O(rows · cols) aikaa, O(1) lisämuistia tulosteen lisäksi. Kuori matriisia kerros kerrokselta neljällä rajalla; kaksi ehtoa estävät viimeisen yksittäisen rivin tai sarakkeen lukemisen kahdesti. ```python def spiral(matrix: list[list[int]]) -> list[int]: out = [] if not matrix or not matrix[0]: return out top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1 while top <= bottom and left <= right: out.extend(matrix[top][c] for c in range(left, right + 1)) out.extend(matrix[r][right] for r in range(top + 1, bottom + 1)) if top < bottom: out.extend(matrix[bottom][c] for c in range(right - 1, left - 1, -1)) if left < right: out.extend(matrix[r][left] for r in range(bottom - 1, top, -1)) top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1 return out ``` Miksi tämä toimii: - Lue neljä sivua vaaditussa suunnassa. - Suojaa kolmas ja neljäs sivu, jotta yksittäistä riviä tai saraketta ei lueta kahdesti. **Vaativuus:** O(rows · cols) aikaa, O(1) lisämuistia tulosteen lisäksi. ``` ## code.hard.rate_limiter.class (fi) **user** ```text **Liukuvan ikkunan rajoitin** Toteuta `RateLimiter(limit, window)`, jossa on `allow(t)`. Kutsu hetkellä `t` sallitaan, jos ikkunassa `(t - window, t]` on ollut alle `limit` sallittua kutsua; sallitut kutsut kirjataan, hylätyt eivät. Ajat eivät koskaan pienene. Käytä tasattua O(1)-aikaa kutsua kohden. Allekirjoitus: ```python class RateLimiter: def __init__(self, limit: int, window: int): ... def allow(self, t: int) -> bool: ... ``` Esimerkki: ```python obj = RateLimiter(1, 3) obj.allow(1) # True obj.allow(1) # False obj.allow(4) # True obj.allow(4) # False obj.allow(7) # True obj.allow(8) # False obj.allow(8) # False ``` Toteuta Pythonilla ja lisää assert-testit, jotka kattavat reunatapaukset. ``` **assistant** ```text - Vain sallitut kutsut lasketaan rajaan. - Ikkuna on puoliavoin: tasan `window` sitten tehty kutsu ei enää lasketa (x <= t - window poistuu). - Ajat eivät pienene, joten vanhentuneet ovat aina alussa: deque antaa tasatun O(1):n. - Reunatapaukset: purske samalla hetkellä, raja 1, ikkunaa pidemmät tauot. - Vaativuus: tasattu O(1) kutsua kohden, O(limit) muistia. Pidä sallittujen kutsujen ajat deque-jonossa; poista vasemmalta ikkunasta pudonneet ajat ja salli, jos jäljellä on alle `limit`. ```python from collections import deque class RateLimiter: def __init__(self, limit: int, window: int): self.limit, self.window = limit, window self.accepted = deque() # times of accepted calls inside the window def allow(self, t: int) -> bool: # t never decreases while self.accepted and self.accepted[0] <= t - self.window: self.accepted.popleft() if len(self.accepted) < self.limit: self.accepted.append(t) return True return False ``` **Vaativuus:** tasattu O(1) kutsua kohden, O(limit) muistia. Testit: ```python obj = RateLimiter(2, 5) assert obj.allow(3) assert obj.allow(4) assert not obj.allow(7) assert obj.allow(12) assert obj.allow(12) assert obj.allow(17) assert obj.allow(18) obj = RateLimiter(1, 10) assert obj.allow(0) assert not obj.allow(9) assert obj.allow(10) ``` Kaikki nämä assertit menevät läpi yllä olevalla ratkaisulla. ``` ## code.hard.cheapest_path.k (en) **user** ```text **Cheapest route with at most k stops** There are `n` cities `0..n-1` and one-way flights `[u, v, price]`. Return the cheapest total price from `src` to `dst` using at most `k` intermediate stops (so at most k + 1 flights), or -1 if no such route exists. Prices are positive. Signature: ```python def cheapest_price(n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int: ``` Examples: ```python >>> cheapest_price(2, [[1, 0, 29]], 1, 1, 2) 0 >>> cheapest_price(2, [[1, 0, 36], [0, 1, 17], [0, 1, 23]], 0, 1, 3) 17 ``` Write the solution in Python and include a few tests. ``` **assistant** ```text Bellman-Ford limited to k + 1 rounds: each round relaxes every flight once from a copy of the previous round's costs, so a route never uses more flights than rounds. ```python def cheapest_price(n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int: INF = float("inf") cost = [INF] * n cost[src] = 0 for _ in range(k + 1): nxt = cost[:] for u, v, price in flights: if cost[u] + price < nxt[v]: nxt[v] = cost[u] + price cost = nxt return cost[dst] if cost[dst] < INF else -1 ``` **Complexity:** O((k + 1) · E) time, O(n) space. Tests: ```python assert cheapest_price(2, [[1, 0, 29]], 1, 1, 2) == 0 assert cheapest_price(2, [[1, 0, 36], [0, 1, 17], [0, 1, 23]], 0, 1, 3) == 17 assert cheapest_price(3, [[0, 1, 1], [1, 2, 1], [0, 2, 5]], 0, 2, 0) == 5 assert cheapest_price(3, [[0, 1, 5]], 0, 2, 1) == -1 assert cheapest_price(3, [[0, 1, 5]], 0, 0, 0) == 0 ``` All of these assertions pass against the solution above. ``` ## code.hard.inversions.plain (en) **user** ```text **Count inversions** Return the number of index pairs `i < j` with `a[i] > a[j]`. Values can be negative and the list can have 150,000 elements, so checking every pair is too slow. Signature: ```python def count_inversions(a: list[int]) -> int: ``` Examples: ```python >>> count_inversions([-3, -3, -3, -6, -1, -3, -2, 3, 5, -6]) 13 >>> count_inversions([9, 9, 5]) 2 ``` Implement it in Python. ``` **assistant** ```text Merge sort that counts: pairs inside each half are counted recursively, and pairs across the halves are counted in linear time because both halves are sorted. ```python def count_inversions(a: list[int]) -> int: def sort_count(xs): if len(xs) <= 1: return xs, 0 mid = len(xs) // 2 left, inv_left = sort_count(xs[:mid]) right, inv_right = sort_count(xs[mid:]) inv = inv_left + inv_right i = j = 0 merged = [] while i < len(left) and j < len(right): if left[i] <= right[j]: merged.append(left[i]) i += 1 else: merged.append(right[j]) inv += len(left) - i # right[j] is smaller than every remaining left element j += 1 merged += left[i:] + right[j:] return merged, inv return sort_count(list(a))[1] ``` **Complexity:** O(n log n) time, O(n) space. ``` ## code.hard.knapsack.01 (fi) **user** ```text **Reppuongelma (0/1)** Esine i painaa `weights[i]` ja on arvoltaan `values[i]` (kaikki positiivisia kokonaislukuja). Palauta suurin kokonaisarvo, jonka kokonaispaino on enintään `capacity`; jokaisen esineen voi ottaa enintään kerran. Allekirjoitus: ```python def best_load(weights: list[int], values: list[int], capacity: int) -> int: ``` Esimerkit: ```python >>> best_load([6, 9, 2, 8, 2, 8, 11, 1], [6, 37, 37, 48, 10, 56, 20, 29], 16) 132 >>> best_load([7, 11, 3], [36, 19, 21], 8) 36 ``` Toteuta se Pythonilla. ``` **assistant** ```text - Osajoukkojen läpikäynti on 2^n; kapasiteetti on pieni, joten DP kapasiteetin yli on O(n · capacity). - best[c] = max(best[c], best[c - w] + v). - Silmukan suunta ratkaisee uudelleenkäytön: alaspäin 0/1, ylöspäin rajoittamaton. - Reunatapaukset: ei esineitä, liian painavat esineet, kapasiteetti 0. - Vaativuus: O(n · capacity) aikaa, O(capacity) muistia. Yksiulotteinen DP kapasiteetin yli: best[c] on paras arvo kapasiteetilla c. Kun c käydään alaspäin, samaa esinettä ei lasketa kahdesti. ```python def best_load(weights: list[int], values: list[int], capacity: int) -> int: best = [0] * (capacity + 1) for w, v in zip(weights, values): for c in range(capacity, w - 1, -1): # downwards: each item is used at most once if best[c - w] + v > best[c]: best[c] = best[c - w] + v return best[capacity] ``` **Vaativuus:** O(n · capacity) aikaa, O(capacity) muistia. ``` ## code.hard.primes_range.sieve (fi) **user** ```text **Laske alkuluvut välillä** Palauta, kuinka monta alkulukua `p` toteuttaa ehdon `lo <= p <= hi`. `lo` voi olla negatiivinen, ja `lo > hi` tarkoittaa tyhjää väliä. `hi` voi olla jopa 8 000 000. Allekirjoitus: ```python def count_primes(lo: int, hi: int) -> int: ``` Esimerkit: ```python >>> count_primes(128, 180) 10 >>> count_primes(10, 103) 23 ``` Kirjoita ratkaisu Pythonilla ja lisää muutama testi. ``` **assistant** ```text - Jakokokeilu luku kerrallaan on liian hidas 8 miljoonalle; seulo kerran. - Aloita merkintä luvusta p*p; pienemmät on käsitelty pienemmillä alkuluvuilla. - Viipalesijoitus bytearray-taulukkoon on paljon nopeampi kuin Python-silmukka. - Reunatapaukset: hi < 2, negatiivinen lo, lo > hi, lo == hi. - Vaativuus: O(hi log log hi) aikaa, O(hi) muistia. Eratostheneen seula bytearray-taulukossa lukuun hi asti (viipalesijoitus merkitsee monikerrat nopeasti) ja flagien summa välillä [lo, hi]. ```python def count_primes(lo: int, hi: int) -> int: if hi < 2 or lo > hi: return 0 sieve = bytearray([1]) * (hi + 1) sieve[0] = sieve[1] = 0 p = 2 while p * p <= hi: if sieve[p]: sieve[p * p::p] = bytes(len(range(p * p, hi + 1, p))) p += 1 return sum(sieve[max(lo, 0):hi + 1]) ``` **Vaativuus:** O(hi log log hi) aikaa, O(hi) muistia. Testit: ```python assert count_primes(128, 180) == 10 assert count_primes(10, 103) == 23 assert count_primes(97, 97) == 1 assert count_primes(0, 1) == 0 assert count_primes(-10, 10) == 4 ``` Kaikki nämä assertit menevät läpi yllä olevalla ratkaisulla. ```