Compute Running Departmental Budget Consumed
SQL & DataAuto-graded · 13 test casesLast updated
Tests ability to implement window-style running totals by computing each row's cumulative spend within its department, ordered by date then transaction ID.
Running Departmental Budget Consumed
You are given a list of expense transactions. Each transaction is a dictionary with the following fields:
"txn_id"(int): unique transaction identifier"dept"(str): department name"date"(str): date in"YYYY-MM-DD"format"amount"(float or int): the expense amount (always non-negative)
Your task is to compute, for each transaction, the cumulative amount spent by its department up to and including that transaction, where transactions within a department are ordered by "date" ascending, breaking ties by "txn_id" ascending.
Return a list of dicts, one per input transaction, each containing:
"txn_id"(int): same as input"dept"(str): same as input"running_total"(float): the cumulative sum for that department through this transaction (in the ordering defined above)
The output list must be sorted by "txn_id" ascending (i.e. restore the natural transaction order).
Constraints
0 <= len(transactions) <= 2000- Each
"txn_id"is a unique positive integer. "date"strings are always valid dates in"YYYY-MM-DD"format.0 <= amount <= 10_000- Department names are non-empty strings.
- If
transactionsis empty, return an empty list.
Examples
Example 1
Input: running_dept_totals([{'txn_id': 1, 'dept': 'Engineering', 'date': '2024-01-10', 'amount': 500}, {'txn_id': 2, 'dept': 'Marketing', 'date': '2024-01-08', 'amount': 200}, {'txn_id': 3, 'dept': 'Engineering', 'date': '2024-01-15', 'amount': 300}, {'txn_id': 4, 'dept': 'Marketing', 'date': '2024-01-20', 'amount': 150}])
Output: [{'txn_id': 1, 'dept': 'Engineering', 'running_total': 500}, {'txn_id': 2, 'dept': 'Marketing', 'running_total': 200}, {'txn_id': 3, 'dept': 'Engineering', 'running_total': 800}, {'txn_id': 4, 'dept': 'Marketing', 'running_total': 350}]
Example 2
Input: running_dept_totals([{'txn_id': 10, 'dept': 'HR', 'date': '2024-03-01', 'amount': 100}, {'txn_id': 11, 'dept': 'HR', 'date': '2024-03-01', 'amount': 200}, {'txn_id': 12, 'dept': 'HR', 'date': '2024-03-01', 'amount': 50}])
Output: [{'txn_id': 10, 'dept': 'HR', 'running_total': 100}, {'txn_id': 11, 'dept': 'HR', 'running_total': 300}, {'txn_id': 12, 'dept': 'HR', 'running_total': 350}]
Example 3
Input: running_dept_totals([])
Output: []
Hints
Hint 1
Group transactions by department first, then sort each group by (date, txn_id) to establish the window ordering.
Hint 2
Iterate through each department's sorted transactions, accumulating a running sum as you go.
Hint 3
After computing running totals, re-sort all results by txn_id to match the required output order.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is the Python equivalent of a SQL SUM(...) OVER (PARTITION BY dept ORDER BY date, txn_id) window function.
Steps:
-
Group by department. Use a
defaultdict(list)to collect all transactions belonging to each department. -
Sort within each group. For each department's list, sort by
(date, txn_id)ascending. Since date strings are inYYYY-MM-DDformat, lexicographic string comparison is equivalent to chronological order. -
Compute the running total. Walk through the sorted list once, accumulating a running sum. Emit a result dict for each transaction.
-
Restore global output order. Sort all result dicts by
txn_idascending.
Why it is correct: Sorting by (date, txn_id) perfectly mirrors SQL's ORDER BY date, txn_id clause inside the window frame. Grouping first ensures the running total resets per department, mirroring PARTITION BY dept. The final sort restores the "natural" transaction order without disturbing the per-department running totals already computed.
Time complexity: O(n log n) — dominated by sorting (globally and per department).
Space complexity: O(n) — for the grouped and result lists.
from collections import defaultdict
def running_dept_totals(transactions: list) -> list:
if not transactions:
return []
# Group by department
dept_groups = defaultdict(list)
for txn in transactions:
dept_groups[txn["dept"]].append(txn)
# For each department, sort by (date, txn_id) and compute running total
result = []
for dept, txns in dept_groups.items():
txns_sorted = sorted(txns, key=lambda t: (t["date"], t["txn_id"]))
running = 0.0
for txn in txns_sorted:
running += txn["amount"]
result.append({
"txn_id": txn["txn_id"],
"dept": dept,
"running_total": running
})
# Restore output order by txn_id
result.sort(key=lambda r: r["txn_id"])
return result