Compute Per-Group Running Revenue Share with Reset
SQL & DataAuto-graded · 15 test casesLast updated
Tests window-style running totals and per-group aggregation by computing a cumulative percentage-of-group-total that resets for each new group, given pre-sorted row data.
Running Revenue Share Within Groups
You are given a table of sales transactions represented as a list of rows. Each row is a dict with three keys:
"group"— a string identifying the sales region (e.g."North","South")"order"— a non-negative integer giving the position of this row within its group (unique per group, but not necessarily contiguous or starting at 0)"revenue"— a non-negative integer
Your task is to simulate a window function that computes, for every row, the cumulative revenue share of that row within its group.
Concretely, for each group independently:
- Sort the rows by
"order"ascending. - Compute
group_total= sum of all"revenue"values in the group. - For the i-th row (0-indexed after sorting), compute the running sum of revenue through and including row i (i.e., rows 0 … i).
- The cumulative share for that row =
running_sum / group_total, rounded to 4 decimal places.- Special case: if
group_total == 0, every row in that group gets a cumulative share of0.0.
- Special case: if
Return a new list of dicts, one per input row, each containing exactly the keys:
"group"— same as input"order"— same as input"revenue"— same as input"cumulative_share"— the float value described above (rounded to 4 decimal places)
The output list must be sorted first by "group" ascending (lexicographic), then by "order" ascending within each group.
Constraints
0 <= len(rows) <= 2000- Each
"group"value is a non-empty string containing only uppercase and lowercase ASCII letters. - Within a single group, all
"order"values are distinct non-negative integers (0 <= order <= 10^6). 0 <= revenue <= 10^6- The input list may arrive in any order; do not assume it is pre-sorted.
- Group names are case-sensitive (
"north"and"North"are different groups). - If
rowsis empty, return[].
Examples
Example 1
Input: running_revenue_share([{'group': 'North', 'order': 1, 'revenue': 100}, {'group': 'North', 'order': 2, 'revenue': 200}, {'group': 'North', 'order': 3, 'revenue': 200}, {'group': 'South', 'order': 10, 'revenue': 400}, {'group': 'South', 'order': 20, 'revenue': 100}])
Output: [{'group': 'North', 'order': 1, 'revenue': 100, 'cumulative_share': 0.2}, {'group': 'North', 'order': 2, 'revenue': 200, 'cumulative_share': 0.6}, {'group': 'North', 'order': 3, 'revenue': 200, 'cumulative_share': 1}, {'group': 'South', 'order': 10, 'revenue': 400, 'cumulative_share': 0.8}, {'group': 'South', 'order': 20, 'revenue': 100, 'cumulative_share': 1}]
Example 2
Input: running_revenue_share([{'group': 'A', 'order': 5, 'revenue': 0}, {'group': 'A', 'order': 3, 'revenue': 0}, {'group': 'A', 'order': 8, 'revenue': 0}])
Output: [{'group': 'A', 'order': 3, 'revenue': 0, 'cumulative_share': 0}, {'group': 'A', 'order': 5, 'revenue': 0, 'cumulative_share': 0}, {'group': 'A', 'order': 8, 'revenue': 0, 'cumulative_share': 0}]
Example 3
Input: running_revenue_share([{'group': 'West', 'order': 0, 'revenue': 1000}])
Output: [{'group': 'West', 'order': 0, 'revenue': 1000, 'cumulative_share': 1}]
Hints
Hint 1
First, bucket the rows by group name using a dict, then sort each bucket by 'order' — this mirrors how SQL partitions and orders a window frame.
Hint 2
Compute the group total in one pass, then iterate again keeping a running sum; divide running_sum by group_total at each step (handle the zero-total edge case separately).
Hint 3
Collect all output dicts into one list and sort by (group, order) at the end; round with Python's built-in round(x, 4) to get exactly 4 decimal places.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem directly mirrors the SQL pattern:
SUM(revenue) OVER (PARTITION BY group ORDER BY order ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
/ SUM(revenue) OVER (PARTITION BY group)
Steps
- Partition — use a
defaultdict(list)to collect rows by"group". - Sort within partition — sort each bucket by
"order"ascending, mirroringORDER BY order. - Two-pass per group:
- First pass (or a simple
sum): computegroup_total. - Second pass: maintain a
running_sum; after adding each row's revenue,share = running_sum / group_total(rounded to 4 dp). Ifgroup_total == 0, emit0.0for all rows.
- First pass (or a simple
- Final sort — sort the combined output list by
("group", "order")for a deterministic, canonical ordering.
Why it is correct
- Sorting by
"order"before the running-sum pass guarantees the cumulative sum is computed in the correct frame order. - The zero-total guard prevents division by zero; 0/0 is canonically defined as 0.0 here.
round(..., 4)gives a consistent 4-decimal-place float regardless of floating-point representation noise.
Complexity
- Time: O(N log N) overall — dominated by the sort inside each group (the final sort is also O(N log N)).
- Space: O(N) for the group buckets and output list.
from typing import List, Dict, Any
from collections import defaultdict
def running_revenue_share(rows: list) -> list:
if not rows:
return []
groups: Dict[str, list] = defaultdict(list)
for row in rows:
groups[row["group"]].append(row)
result = []
for group_name, group_rows in groups.items():
group_rows.sort(key=lambda r: r["order"])
group_total = sum(r["revenue"] for r in group_rows)
running_sum = 0
for row in group_rows:
running_sum += row["revenue"]
if group_total == 0:
share = 0.0
else:
share = round(running_sum / group_total, 4)
result.append({
"group": row["group"],
"order": row["order"],
"revenue": row["revenue"],
"cumulative_share": share,
})
result.sort(key=lambda r: (r["group"], r["order"]))
return result