Aggregate Sales Data with Running and Grand Totals
Data Structure DesignAuto-graded · 20 test casesLast updated
Tests dictionary aggregation, deterministic ordering, and building cumulative totals along two dimensions from grouped records.
You are building an analytics tool that aggregates sales records. Each record is a dictionary containing a store identifier, transaction date, product color, item size, and the quantity of shirts sold:
{
"Store ID": "abcd1234",
"Date": "2021-05-25",
"Color": "red",
"Size": "XS",
"Shirts sold": 1
}
Your task is to write a function that produces a multidimensional summary by grouping records along two axes—one for rows and one for columns—and computing aggregate statistics.
Given a list of sales records, a row field name, a column field name, and a value field name, produce a dictionary containing:
- Distinct values for the row and column fields, in order of first appearance
- Aggregated values: a 2D grid where each cell sums the value field for all records matching that row and column combination (use
0if no records match) - Row running totals: for each row, cumulative sums from left to right across columns
- Column running totals: for each column, cumulative sums from top to bottom down rows
- Row totals: sum of all values in each row
- Column totals: sum of all values in each column
- Grand total: sum of all values across the entire table
Return a dictionary with these keys:
"rows": list of distinct row field values in order of first appearance"columns": list of distinct column field values in order of first appearance"values": 2D list (list of lists) wherevalues[r][c]is the sum for rowrand columnc"row_running": 2D list whererow_running[r][c]is the cumulative sum ofvalues[r][0]throughvalues[r][c]"column_running": 2D list wherecolumn_running[r][c]is the cumulative sum ofvalues[0][c]throughvalues[r][c]"row_totals": list whererow_totals[r]is the sum of rowr"column_totals": list wherecolumn_totals[c]is the sum of columnc"grand_total": integer sum of all values
Field names match exactly as they appear in the records, including spaces and capitalization (e.g., "Store ID", "Shirts sold").
Constraints
- 1 ≤ number of records ≤ 10,000
- All records contain the specified row, column, and value fields
- Value field contains non-negative integers
- Row and column field values are strings
- Order of rows and columns is determined by first appearance in the input list
Examples
Example 1
Input: build_pivot_table([{'Store ID': 'abcd1234', 'Date': '2021-05-25', 'Color': 'red', 'Size': 'XS', 'Shirts sold': 1}, {'Store ID': 'abcd1234', 'Date': '2021-05-25', 'Color': 'blue', 'Size': 'L', 'Shirts sold': 20}, {'Store ID': 'abcd1234', 'Date': '2021-05-25', 'Color': 'green', 'Size': 'M', 'Shirts sold': 300}, {'Store ID': 'abcd1234', 'Date': '2021-05-26', 'Color': 'red', 'Size': 'XS', 'Shirts sold': 4}, {'Store ID': 'abcd1234', 'Date': '2021-05-26', 'Color': 'black', 'Size': 'S', 'Shirts sold': 50}, {'Store ID': '5678wxyz', 'Date': '2021-05-25', 'Color': 'blue', 'Size': 'XL', 'Shirts sold': 600}, {'Store ID': '5678wxyz', 'Date': '2021-05-25', 'Color': 'green', 'Size': 'M', 'Shirts sold': 7}, {'Store ID': '5678wxyz', 'Date': '2021-05-25', 'Color': 'black', 'Size': 'L', 'Shirts sold': 80}, {'Store ID': '5678wxyz', 'Date': '2021-05-26', 'Color': 'blue', 'Size': 'S', 'Shirts sold': 900}, {'Store ID': 'e1f9g2h8', 'Date': '2021-05-26', 'Color': 'red', 'Size': 'S', 'Shirts sold': 1}, {'Store ID': 'e1f9g2h8', 'Date': '2021-05-27', 'Color': 'black', 'Size': 'M', 'Shirts sold': 20}], 'Store ID', 'Color', 'Shirts sold')
Output: {'rows': ['abcd1234', '5678wxyz', 'e1f9g2h8'], 'columns': ['red', 'blue', 'green', 'black'], 'values': [[5, 20, 300, 50], [0, 1500, 7, 80], [1, 0, 0, 20]], 'row_running': [[5, 25, 325, 375], [0, 1500, 1507, 1587], [1, 1, 1, 21]], 'column_running': [[5, 20, 300, 50], [5, 1520, 307, 130], [6, 1520, 307, 150]], 'row_totals': [375, 1587, 21], 'column_totals': [6, 1520, 307, 150], 'grand_total': 1983}
Example 2
Input: build_pivot_table([{'Store ID': 's1', 'Date': '2024-01-01', 'Color': 'red', 'Size': 'S', 'Shirts sold': 5}, {'Store ID': 's1', 'Date': '2024-01-02', 'Color': 'red', 'Size': 'M', 'Shirts sold': 2}, {'Store ID': 's2', 'Date': '2024-01-01', 'Color': 'blue', 'Size': 'L', 'Shirts sold': 8}, {'Store ID': 's2', 'Date': '2024-01-02', 'Color': 'red', 'Size': 'S', 'Shirts sold': 1}], 'Color', 'Store ID', 'Shirts sold')
Output: {'rows': ['red', 'blue'], 'columns': ['s1', 's2'], 'values': [[7, 1], [0, 8]], 'row_running': [[7, 8], [0, 8]], 'column_running': [[7, 1], [7, 9]], 'row_totals': [8, 8], 'column_totals': [7, 9], 'grand_total': 16}
Example 3
Input: build_pivot_table([{'Store ID': 'only', 'Date': '2024-01-01', 'Color': 'black', 'Size': 'XS', 'Shirts sold': 0}], 'Date', 'Size', 'Shirts sold')
Output: {'rows': ['2024-01-01'], 'columns': ['XS'], 'values': [[0]], 'row_running': [[0]], 'column_running': [[0]], 'row_totals': [0], 'column_totals': [0], 'grand_total': 0}
Hints
Hint 1
Track the order in which unique row and column values appear by maintaining both a list and a dictionary index.
Hint 2
Build the aggregated grid first, then derive running totals by iterating left-to-right for rows and top-to-bottom for columns.
Hint 3
Verify correctness by checking that the sum of row totals equals the sum of column totals, which equals the grand total.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution builds a pivot table in three phases: discovering dimensions, aggregating values, and computing cumulative statistics.
Phase 1: Discover dimensions
Iterate through all records once to identify unique row and column values. Maintain their first-appearance order using a list for ordering and a dictionary for O(1) lookup of each value's index position.
Phase 2: Aggregate values
Initialize a 2D grid with zeros, sized by the number of unique rows and columns. For each record, look up the row and column indices and add the value field to the corresponding cell.
Phase 3: Compute totals
- Row running totals: For each row, accumulate values left-to-right, storing the cumulative sum at each position
- Column running totals: For each column, accumulate values top-to-bottom as you traverse rows
- Row and column totals: Sum each row and each column independently
- Grand total: Sum all row totals (or equivalently, all column totals)
The row totals and column totals must sum to the same grand total, providing a built-in consistency check.
Why this works: The aggregation correctly groups records by their row and column field values. Running totals follow the deterministic ordering established during dimension discovery, ensuring consistency between the values grid and all derived statistics.
Time complexity: O(n + r×c) where n is the number of records, r is the number of unique row values, and c is the number of unique column values. The first pass discovers dimensions in O(n), aggregation is O(n), and computing totals is O(r×c).
Space complexity: O(r×c) for storing the values grid and running totals, plus O(r + c) for the dimension lists and indices.
from typing import List, Dict
def build_pivot_table(records: List[Dict[str, object]], row_field: str, column_field: str, value_field: str) -> Dict[str, object]:
rows = []
columns = []
row_index = {}
column_index = {}
for record in records:
row_value = record[row_field]
column_value = record[column_field]
if row_value not in row_index:
row_index[row_value] = len(rows)
rows.append(row_value)
if column_value not in column_index:
column_index[column_value] = len(columns)
columns.append(column_value)
values = [[0 for _ in columns] for _ in rows]
for record in records:
r = row_index[record[row_field]]
c = column_index[record[column_field]]
values[r][c] += record[value_field]
row_running = []
for row in values:
running = 0
prefixes = []
for value in row:
running += value
prefixes.append(running)
row_running.append(prefixes)
column_running = [[0 for _ in columns] for _ in rows]
column_totals = [0 for _ in columns]
for r, row in enumerate(values):
for c, value in enumerate(row):
column_totals[c] += value
column_running[r][c] = column_totals[c]
row_totals = [sum(row) for row in values]
grand_total = sum(row_totals)
return {
"rows": rows,
"columns": columns,
"values": values,
"row_running": row_running,
"column_running": column_running,
"row_totals": row_totals,
"column_totals": column_totals,
"grand_total": grand_total,
}