CodeKitchen prep
0%
Contest in--:--:--
Practice Β· lesson 11/13

βš—οΈPython lab (live judge)

⏳ ~25 min

These run your code in real Python against hidden-style tests. stdin β†’ stdout problems compare your output line by line (trailing spaces are ignored); function problems call your function directly. Press Tab / Shift+Tab to indent and Ctrl+Enter to run.

Read input from sys.stdin (read(), buffer.read(), readline(), or input()). open(0) is not supported here. On the PHP-hosted version your code runs in your browser (Pyodide). The first run downloads the runtime, about 10 MB.

Think like the judge: after the samples pass, ask yourself what's the empty case, what are the ties, what happens with a 10⁢-row input? Each exercise has at least one hidden-style edge case.

Warm-up

easy

Fast IO warm-up: totals per user

stdin β†’ stdoutβœ“ solved
Input: first line n, then n lines user_id,amount (amount is a decimal, may be negative for refunds; lines may have surrounding spaces).
Output: one line per user user_id total sorted by user_id as a string, total with exactly 2 decimals.
easy

Flatten nested JSON

implement flatten()βœ“ solved
Implement flatten(obj): turn nested dicts/lists into a flat dict with dot-joined keys. List elements use their index. Empty dicts/lists are kept as values. Example:
{"a": {"b": 1, "c": [10, {"d": 2}]}, "e": {}} β†’ {"a.b": 1, "a.c.0": 10, "a.c.1.d": 2, "e": {}}
easy

Deduplicate CDC records

implement dedupe_latest()βœ“ solved
dedupe_latest(records): records are dicts with keys id, updated_at (ISO string) and other fields. Keep, for each id, the record with the greatest updated_at; if two records tie, keep the one that appears later in the input. Return the list sorted by id.
easy

Merge overlapping intervals

implement merge_intervals()βœ“ solved
merge_intervals(intervals): intervals is an unsorted list of (start, end) pairs. Merge every pair that overlaps or touches ((1, 5) and (5, 7) β†’ (1, 7)). Return a list of tuples sorted by start.

Pipeline logic

medium

Sessionize events

implement sessionize()βœ“ solved
sessionize(events, gap): events is an unsorted list of (user, ts) with ts in seconds. A new session starts when the gap to the user's previous event is strictly greater than gap. Return a list of (user, start, end, count) sorted by user then start.
medium

Schema validation / data quality

implement validate()βœ“ solved
validate(rows, schema). schema maps column β†’ (type, required), type in "int" | "float" | "str". For each row (index i) and each schema column (in schema order) report:
  • (i, col, "missing") if the key is absent or None and the column is required (optional missing β†’ fine)
  • (i, col, "type") if present but wrong type. int accepts ints but not bools; float accepts int or float (not bool); str accepts str.
  • (i, col, "unknown") for each key not in the schema β€” reported after schema columns, keys sorted.
Return the list of errors in order of row index.
medium

Log parsing: top-K endpoints

stdin β†’ stdoutβœ“ solved
First line: K. Then access-log lines until EOF, e.g. 10.0.0.1 - - [23/Oct/2026:10:00:01 +0330] "GET /api/orders?id=3 HTTP/1.1" 200 512. Some lines are malformed β€” skip them. Count requests per path without query string. Print the top K as path hits errors where errors = number of 5xx responses. Sort by hits desc, then path asc.
medium

pandas: customer summary

implement customer_summary()βœ“ solved
customer_summary(df): df has columns customer_id, order_date (string YYYY-MM-DD), amount, status. Using only status == "completed" rows, return a DataFrame with columns customer_id, orders, total, first_order, last_order (dates as strings), sorted by total desc then customer_id asc, with a fresh 0..n-1 index. (The judge compares df.to_dict("records").)
medium

As-of join: price at trade time

implement asof_join()βœ“ solved
asof_join(trades, rates): trades is a list of (ts, amount), rates an unsorted list of (ts, rate). For every trade, in input order, return round(amount * rate, 2) using the latest rate whose ts is <= the trade's ts, or None if no such rate exists. Aim for O((n + m) log m).
medium

LRU cache simulation

implement lru_simulate()βœ“ solved
lru_simulate(capacity, requests): simulate an LRU cache of size capacity over a list of keys. A request for a cached key is a hit (and makes it most recently used); otherwise it's a miss, the key is inserted, and if the cache is over capacity the least recently used key is evicted. Return (hits, misses, keys) where keys is the final cache content from least to most recently used.
medium

Peak concurrent sessions (sweep line)

implement peak_concurrency()βœ“ solved
peak_concurrency(sessions): each session is a half-open interval [start, end), so a session ending at t does not overlap one starting at t. Return (peak, first_time): the maximum number of simultaneous sessions and the earliest time that maximum is reached. For no sessions return (0, None).

Hard

medium

Pipeline DAG: execution order

implement run_order()βœ“ solved
run_order(deps): deps maps task β†’ list of tasks it depends on (dependencies may not appear as keys themselves). Return an execution order where every task comes after its dependencies, choosing the alphabetically smallest available task at each step. If there is a cycle return None.
hard

Slowly Changing Dimension type 2

implement apply_scd2()βœ“ solved
apply_scd2(dim, changes). dim: list of rows {"id", "attr", "valid_from", "valid_to"} (current row has valid_to=None). changes: list of (id, attr, date) β€” process them in date order (stable for equal dates):
  • unknown id β†’ insert a new current row (valid_from=date)
  • current attr differs β†’ close current row (valid_to=date) and insert a new current row
  • same attr β†’ no-op (idempotent!)
Return all rows sorted by (id, valid_from). Don't mutate the input.

Reading a failing test

  • your output is empty β†’ you never printed, printed inside a function you didn't call, or crashed before the final write (check error).
  • Output matches except the last lines β†’ you forgot to flush the final group (the "last session" bug).
  • got shows [[1, 2]] but expected shows [(1, 2)] β†’ tuples vs lists. A judge comparing with == treats them as different.
  • None returned β†’ you built the result but forgot return.
  • KeyError / IndexError on the empty test β†’ guard lines[0] and empty lists before indexing.

Finished the lab? Go to the Mock contest lesson for six new problems against the clock.

🏁 --:--