Compute Per-Category Running Revenue with Reset on Loss
SQL & DataAuto-graded · 15 test casesLast updated
Tests ability to implement window-style running totals that accumulate per category but reset to zero whenever a loss (negative value) would pull the running total below zero.
Running Revenue Tracker with Floor Reset
You are given a table of daily transaction records, each belonging to a named category. Your task is to compute a per-category running total of the amount column, ordered by day, with one special rule:
Whenever adding the current row's
amountwould cause the running total to drop below zero, the running total resets to0before continuing (i.e., the running total is floored at0after each addition).
More precisely, for each category independently and in ascending day order:
running_total[i] = max(0, running_total[i-1] + amount[i])
with running_total starting at 0 before the first row of each category.
Input
A function running_revenue(records, categories):
records: a list of dicts, each with:"category"(str): the category name"day"(int): the day number (1-indexed; unique per category, but two records from different categories may share the same day)"amount"(int or float): the transaction amount (may be negative)
categories: a list of category name strings specifying which categories to include in the output and in what order.
Output
Return a list of dicts, one per input record that belongs to a category listed in categories, sorted first by the order of categories (i.e., the position of the record's category in the categories list), then by ascending day within each category.
Each output dict has exactly three keys:
"category"(str)"day"(int)"running_total"(float): the running total after applying the floor rule, as a Pythonfloat.
Records whose "category" is not in categories are silently dropped.
If two records in records share the same (category, day) pair, treat the one that appears later in the records list as overriding the earlier one (keep only the last occurrence).
Constraints
0 ≤ len(records) ≤ 20001 ≤ len(categories) ≤ 50- Category names are non-empty strings of at most 30 characters.
1 ≤ day ≤ 10000-10^6 ≤ amount ≤ 10^6amountvalues are integers or floats; running totals must be returned asfloat.categoriescontains no duplicates.- A category listed in
categoriesmay have zero records inrecords(it simply contributes no rows to the output).
Examples
Example 1
Input: running_revenue([{'category': 'food', 'day': 1, 'amount': 100}, {'category': 'food', 'day': 2, 'amount': -40}, {'category': 'food', 'day': 3, 'amount': -80}, {'category': 'food', 'day': 4, 'amount': 50}, {'category': 'tech', 'day': 1, 'amount': 200}, {'category': 'tech', 'day': 2, 'amount': -250}, {'category': 'tech', 'day': 3, 'amount': 75}], ['food', 'tech'])
Output: [{'category': 'food', 'day': 1, 'running_total': 100}, {'category': 'food', 'day': 2, 'running_total': 60}, {'category': 'food', 'day': 3, 'running_total': 0}, {'category': 'food', 'day': 4, 'running_total': 50}, {'category': 'tech', 'day': 1, 'running_total': 200}, {'category': 'tech', 'day': 2, 'running_total': 0}, {'category': 'tech', 'day': 3, 'running_total': 75}]
Example 2
Input: running_revenue([{'category': 'alpha', 'day': 3, 'amount': 10}, {'category': 'alpha', 'day': 1, 'amount': -5}, {'category': 'alpha', 'day': 2, 'amount': 20}, {'category': 'beta', 'day': 1, 'amount': 30}], ['beta', 'alpha'])
Output: [{'category': 'beta', 'day': 1, 'running_total': 30}, {'category': 'alpha', 'day': 1, 'running_total': 0}, {'category': 'alpha', 'day': 2, 'running_total': 20}, {'category': 'alpha', 'day': 3, 'running_total': 30}]
Example 3
Input: running_revenue([{'category': 'x', 'day': 1, 'amount': 50}, {'category': 'x', 'day': 1, 'amount': -10}, {'category': 'y', 'day': 5, 'amount': 999}], ['x', 'y', 'z'])
Output: [{'category': 'x', 'day': 1, 'running_total': 0}, {'category': 'y', 'day': 5, 'running_total': 999}]
Hints
Hint 1
Group the records by category first, keeping only the last occurrence of each (category, day) pair before doing anything else.
Hint 2
Process each category's rows in ascending day order, maintaining a running accumulator that is floored at 0 after every addition — this is the classic 'floor-at-zero running sum' pattern used in finance.
Hint 3
Build the final output by iterating through categories in the order given, then appending each category's sorted rows; don't forget to cast running totals to float.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is a clean simulation of the "floor-at-zero running sum" pattern — the same calculation underlying a Maximum Drawdown floor or a no-overdraft balance model in financial SQL window functions.
Steps
- Build a category order map from the
categorieslist so we know output ordering in O(1). - De-duplicate
(category, day)pairs by iteratingrecordsonce and storinggrouped[cat][day] = amount, so later records silently overwrite earlier ones. - Process each category in
categoriesorder:- Sort its
(day, amount)pairs by day ascending. - Walk through them, maintaining
running = max(0.0, running + amount). - Append a result dict for each row.
- Sort its
- Return the accumulated result list.
Why it is correct
- De-duplication by keeping the last occurrence matches the spec exactly.
max(0, prev + amount)is the exact recurrence stated in the problem.- Iterating
categoriesin order and days within each category in ascending order guarantees the required output sort.
Complexity
| Value | |
|---|---|
| Time | O(N log N) — dominated by sorting days per category; N = len(records) |
| Space | O(N) — for the grouped dict and output list |
from typing import List, Dict, Any
def running_revenue(records: list, categories: list) -> list:
cat_order = {cat: i for i, cat in enumerate(categories)}
cat_set = set(categories)
grouped: Dict[str, Dict[int, Any]] = {cat: {} for cat in categories}
for rec in records:
cat = rec["category"]
if cat not in cat_set:
continue
day = rec["day"]
grouped[cat][day] = rec["amount"] # later overrides earlier
result = []
for cat in categories:
day_amount_pairs = sorted(grouped[cat].items()) # ascending day
running = 0.0
for day, amount in day_amount_pairs:
running = max(0.0, running + amount)
result.append({
"category": cat,
"day": day,
"running_total": float(running),
})
return result