KatInterview

Compute Running Departmental Budget Consumed

SQL & DataAuto-graded · 13 test cases
EasyAuto-gradedSQL & Datawindow functionsrunning totalsdata processing

Last 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 transactions is 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.