Compute Running Department Salary Budget with Resets
SQL & DataAuto-graded · 13 test casesLast updated
Tests the ability to implement window-style running totals that accumulate within groups and reset at group boundaries, mimicking SQL's SUM() OVER (PARTITION BY ... ORDER BY ...).
Running Department Salary Budget
You are given a list of employee records. Each record is a dictionary with the following keys:
"dept"(str): department name"emp_id"(int): unique employee ID"hire_order"(int): the employee's hiring sequence number within the department (1-indexed, unique per department)"salary"(int): annual salary in whole dollars
Your task mirrors a common SQL pattern:
SUM(salary) OVER (PARTITION BY dept ORDER BY hire_order
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
Implement running_dept_salary(records) that returns a new list of dicts, one per input record, each containing exactly four keys:
"dept"(str)"emp_id"(int)"hire_order"(int)"running_total"(int): cumulative salary sum within the department, ordered byhire_order, including the current row
Output ordering: The output list must be sorted first by "dept" (ascending lexicographic), then by "hire_order" (ascending) within each department.
Notes:
- Input records may arrive in any order.
hire_ordervalues within a department are guaranteed to be unique positive integers, but they may not be contiguous (e.g., 1, 3, 5).- Salaries are positive integers.
- If the input list is empty, return an empty list.
Constraints
0 ≤ len(records) ≤ 2000- Department names consist of uppercase English letters only, length 1–20.
1 ≤ hire_order ≤ 10,0001 ≤ salary ≤ 500,000- Each
emp_idis a unique positive integer. - There is at most one record per
(dept, hire_order)pair.
Examples
Example 1
Input: running_dept_salary([{'dept': 'ENG', 'emp_id': 1, 'hire_order': 1, 'salary': 90000}, {'dept': 'ENG', 'emp_id': 2, 'hire_order': 2, 'salary': 85000}, {'dept': 'HR', 'emp_id': 3, 'hire_order': 1, 'salary': 60000}, {'dept': 'ENG', 'emp_id': 4, 'hire_order': 3, 'salary': 95000}, {'dept': 'HR', 'emp_id': 5, 'hire_order': 2, 'salary': 62000}])
Output: [{'dept': 'ENG', 'emp_id': 1, 'hire_order': 1, 'running_total': 90000}, {'dept': 'ENG', 'emp_id': 2, 'hire_order': 2, 'running_total': 175000}, {'dept': 'ENG', 'emp_id': 4, 'hire_order': 3, 'running_total': 270000}, {'dept': 'HR', 'emp_id': 3, 'hire_order': 1, 'running_total': 60000}, {'dept': 'HR', 'emp_id': 5, 'hire_order': 2, 'running_total': 122000}]
Example 2
Input: running_dept_salary([{'dept': 'SALES', 'emp_id': 10, 'hire_order': 5, 'salary': 50000}, {'dept': 'SALES', 'emp_id': 11, 'hire_order': 1, 'salary': 48000}, {'dept': 'SALES', 'emp_id': 12, 'hire_order': 3, 'salary': 52000}])
Output: [{'dept': 'SALES', 'emp_id': 11, 'hire_order': 1, 'running_total': 48000}, {'dept': 'SALES', 'emp_id': 12, 'hire_order': 3, 'running_total': 100000}, {'dept': 'SALES', 'emp_id': 10, 'hire_order': 5, 'running_total': 150000}]
Example 3
Input: running_dept_salary([])
Output: []
Hints
Hint 1
Group the records by department first, then sort each group by hire_order before accumulating the running total.
Hint 2
A running total simply carries a cumulative sum — each new entry's running_total equals the previous running_total plus the current salary.
Hint 3
After computing all per-department running totals, merge all groups back into one list and sort by (dept, hire_order) to match the required output order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a direct Python equivalent of the SQL window function:
SUM(salary) OVER (PARTITION BY dept ORDER BY hire_order
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
Steps
-
Group by department. Use a dictionary (keyed by
dept) to collect all records that belong together. This is thePARTITION BYstep. -
Sort within each group. For each department's list of records, sort ascending by
hire_order. This establishes the ordering frame. -
Accumulate a running total. Walk through the sorted group, keeping a
cumulativeinteger. For each record, add the currentsalarytocumulativeand emit a new dict withrunning_total = cumulative. The reset happens naturally becausecumulativeis reset to 0 for each new department. -
Collect and sort output. Accumulate all output dicts. Sort the final list by
(dept, hire_order)to satisfy the output ordering requirement.
Why It's Correct
- Grouping ensures salaries from different departments never mix.
- Sorting by
hire_orderbefore accumulating guarantees the running total reflects the correct "chronological" order within the department. - Non-contiguous
hire_ordervalues (e.g., 1, 3, 5) are handled seamlessly because we only sort by value — no indexing arithmetic is needed.
Complexity
- Time: O(N log N) — dominated by the sort (over N total records across all departments).
- Space: O(N) — we store one output dict per input record.
from typing import Dict
from collections import defaultdict
def running_dept_salary(records: list) -> list:
if not records:
return []
# Group by department
dept_groups: Dict[str, list] = defaultdict(list)
for rec in records:
dept_groups[rec["dept"]].append(rec)
result = []
# Process each department in sorted order
for dept in sorted(dept_groups.keys()):
group = sorted(dept_groups[dept], key=lambda r: r["hire_order"])
cumulative = 0
for rec in group:
cumulative += rec["salary"]
result.append({
"dept": rec["dept"],
"emp_id": rec["emp_id"],
"hire_order": rec["hire_order"],
"running_total": cumulative,
})
return result