Running Department Budget Balance by Month
SQL & DataAuto-graded · 15 test casesLast updated
Tests the ability to compute a month-over-month running total (cumulative sum) of expenses per department, mimicking a SQL window function with PARTITION BY and ORDER BY.
Running Department Budget Balance
You are given a list of financial transactions. Each transaction is a dictionary with the following fields:
| Field | Type | Description |
|---|---|---|
department | str | Name of the department |
month | int | Month number (1 = January, 12 = December) |
amount | int | Spending amount (can be negative for refunds/credits) |
Your task is to compute, for each (department, month) pair, the running total of amount accumulated from the earliest month up to and including that month, within that department.
This is equivalent to the SQL:
SELECT
department,
month,
SUM(amount) OVER (
PARTITION BY department
ORDER BY month
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM transactions
However, there may be multiple rows with the same (department, month) pair. All rows sharing the same (department, month) must receive the same running_total — equal to the cumulative sum of all amount values for that department through that month (i.e., aggregate the month first, then accumulate).
Return a list of dicts, each with keys "department", "month", and "running_total". The output list must be sorted first by department (ascending alphabetically), then by month (ascending), with one entry per unique (department, month) pair.
Constraints
0 ≤ len(transactions) ≤ 2000- Each
departmentis a non-empty string of lowercase letters and/or spaces. 1 ≤ month ≤ 12-10_000 ≤ amount ≤ 10_000- If
transactionsis empty, return[]. - Months within a department need not be consecutive (gaps are allowed).
- There is no year field; treat all rows as within one fiscal year.
Examples
Example 1
Input: running_department_totals([{'department': 'engineering', 'month': 1, 'amount': 500}, {'department': 'engineering', 'month': 2, 'amount': 300}, {'department': 'marketing', 'month': 1, 'amount': 200}, {'department': 'marketing', 'month': 3, 'amount': 100}])
Output: [{'department': 'engineering', 'month': 1, 'running_total': 500}, {'department': 'engineering', 'month': 2, 'running_total': 800}, {'department': 'marketing', 'month': 1, 'running_total': 200}, {'department': 'marketing', 'month': 3, 'running_total': 300}]
Example 2
Input: running_department_totals([{'department': 'sales', 'month': 2, 'amount': 400}, {'department': 'sales', 'month': 2, 'amount': -150}, {'department': 'sales', 'month': 5, 'amount': 600}])
Output: [{'department': 'sales', 'month': 2, 'running_total': 250}, {'department': 'sales', 'month': 5, 'running_total': 850}]
Example 3
Input: running_department_totals([])
Output: []
Hints
Hint 1
First aggregate all amounts by (department, month) — sum all amounts that share the same pair — before computing any running total.
Hint 2
Sort the (department, month) pairs: alphabetically by department, then numerically by month. Within each department, accumulate the monthly sums in order.
Hint 3
Build the result by iterating through each department's sorted months, carrying a running accumulator that resets to 0 at the start of each new department.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem mirrors the SQL window function pattern:
SUM(amount) OVER (PARTITION BY department ORDER BY month ROWS UNBOUNDED PRECEDING)
implemented purely in Python.
Steps
-
Aggregate by
(department, month): Multiple rows sharing the same pair must be summed together before any running total is computed. Use adefaultdict(int)keyed on(department, month). -
Group months per department: Collect all distinct months for each department.
-
Sort and accumulate: Sort departments alphabetically. Within each department, sort months numerically (1–12). Walk through months in order, maintaining a running accumulator that resets to 0 at the start of each new department.
-
Emit one row per unique
(department, month)pair in the required sorted order.
Why it is correct
- Aggregating first ensures the "same-month, multiple-row" case is handled before the window computation — matching SQL's behavior where
SUM(...) OVER (...)sees the grouped result. - Sorting by department then month guarantees the deterministic output order required.
- The accumulator carries forward only within a department, correctly partitioning by department.
Complexity
- Time: O(N log N) — dominated by sorting, where N = number of unique
(department, month)pairs (at mostlen(transactions)). - Space: O(N) for the aggregation dict and output list.
Reference Solution
from collections import defaultdict
def running_department_totals(transactions: list) -> list:
# Step 1: Aggregate amounts by (department, month)
agg = defaultdict(int)
for tx in transactions:
key = (tx["department"], tx["month"])
agg[key] += tx["amount"]
# Step 2: Group months by department
dept_months = defaultdict(list)
for (dept, month) in agg:
dept_months[dept].append(month)
# Step 3: Sort departments alphabetically, months numerically within each
result = []
for dept in sorted(dept_months.keys()):
months = sorted(dept_months[dept])
running = 0
for month in months:
running += agg[(dept, month)]
result.append({
"department": dept,
"month": month,
"running_total": running
})
return result