Pivot Table Class with Cumulative and Summary Totals
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Apparel retail logs arrive as a list of dictionaries, where each dictionary represents a transaction summary containing attributes such as "Store ID", "Date", "Color", "Size", and a numeric metric such as "Shirts sold".
Design an object-oriented PivotTable class whose constructor stores an input list of record dictionaries and exposes methods to aggregate two-dimensional cross-tabulations, compute cumulative running sums and summary totals along both axes, and format an aligned plain-text table. Also implement the judge entry point build_pivot_table:
class PivotTable:
def __init__(self, records: list[dict[str, object]]) -> None: ...
def pivot(
self, row_field: str, column_field: str, value_field: str
) -> tuple[list[object], list[object], list[list[float]]]: ...
def with_totals(
self, row_field: str, column_field: str, value_field: str
) -> dict[str, object]: ...
def render(
self,
row_field: str,
column_field: str,
value_field: str,
view: str = "values",
show_totals: bool = True,
) -> str: ...
def build_pivot_table(
records: list[dict[str, object]],
row_field: str,
column_field: str,
value_field: str,
) -> dict[str, object]:
...
Aggregation and Layout Rules
- Dynamic Field Selection:
row_fielddefines the vertical (y-axis) grouping key,column_fielddefines the horizontal (x-axis) grouping key, andvalue_fieldnames the numeric quantity summed inside each(row, column)cell. Field names must be matched verbatim (preserving spaces and letter case). - First-Appearance Axis Ordering: Distinct row labels (
rows) and distinct column labels (columns) must appear in the exact order in which they are first encountered while scanningrecordsfrom index0onward—do not sort them alphabetically. Even a record whose numeric value is0registers its row and column labels. - Dense Rectangular Grid (
values): Every row must contain an entry for every column (R x C). Any(row_label, column_label)pair with zero matching records takes cell value0. - Cumulative Running Grids: Computed in the displayed axis order directly from
values:row_running: anR x Cgrid where entry[r][c]equalssum(values[r][0 : c + 1])(accumulating left to right across each row).column_running: anR x Cgrid where entry[r][c]equalssum(values[0 : r + 1][c])(accumulating top to bottom down each column).
- Summary Totals:
row_totals: length-Rlist where entryrsums rowracross all columns.column_totals: length-Clist where entrycsums columncacross all rows.grand_total: overall sum across all cells (0whenrecordsis empty), guaranteed to equal bothsum(row_totals)andsum(column_totals).
- Return Payload & Immutability:
build_pivot_tablereturns a dictionary with keys"rows","columns","values","row_running","column_running","row_totals","column_totals", and"grand_total", without mutating the caller'srecords.PivotTable.renderformats any view ("values","row_running", or"column_running") into a human-readable table with aligned columns.
Examples
Example 1
records = [
{"Store ID": "ny-10", "Date": "2025-03-10", "Color": "navy", "Size": "M", "Shirts sold": 12},
{"Store ID": "ny-10", "Date": "2025-03-10", "Color": "white", "Size": "L", "Shirts sold": 5},
{"Store ID": "ny-10", "Date": "2025-03-11", "Color": "navy", "Size": "S", "Shirts sold": 8},
{"Store ID": "la-20", "Date": "2025-03-10", "Color": "olive", "Size": "M", "Shirts sold": 15},
{"Store ID": "la-20", "Date": "2025-03-11", "Color": "navy", "Size": "XL", "Shirts sold": 4},
{"Store ID": "chi-30", "Date": "2025-03-12", "Color": "white", "Size": "S", "Shirts sold": 9},
]
build_pivot_table(records, "Store ID", "Color", "Shirts sold")
# Output:
# {
# "rows": ["ny-10", "la-20", "chi-30"],
# "columns": ["navy", "white", "olive"],
# "values": [[20, 5, 0], [4, 0, 15], [0, 9, 0]],
# "row_running": [[20, 25, 25], [4, 4, 19], [0, 9, 9]],
# "column_running": [[20, 5, 0], [24, 5, 15], [24, 14, 15]],
# "row_totals": [25, 19, 9],
# "column_totals": [24, 14, 15],
# "grand_total": 53,
# }
Walk-through:
- Stores appear first in order ["ny-10", "la-20", "chi-30"] and colors in order ["navy", "white", "olive"].
- Store "ny-10" sold 12 + 8 = 20 "navy" shirts, 5 "white" shirts, and 0 "olive" shirts ([20, 5, 0]), giving left-to-right running sums [20, 25, 25] and row total 25.
- Both sum(row_totals) = 25 + 19 + 9 and sum(column_totals) = 24 + 14 + 15 equal grand_total = 53.
Example 2
records = [
{"Store ID": "bos-1", "Date": "2025-04-01", "Color": "grey", "Size": "L", "Shirts sold": 6},
{"Store ID": "bos-2", "Date": "2025-04-02", "Color": "teal", "Size": "S", "Shirts sold": 3},
{"Store ID": "bos-1", "Date": "2025-04-01", "Color": "teal", "Size": "L", "Shirts sold": 4},
{"Store ID": "bos-2", "Date": "2025-04-02", "Color": "grey", "Size": "L", "Shirts sold": 2},
]
build_pivot_table(records, "Size", "Date", "Shirts sold")
# Output:
# {
# "rows": ["L", "S"],
# "columns": ["2025-04-01", "2025-04-02"],
# "values": [[10, 2], [0, 3]],
# "row_running": [[10, 12], [0, 3]],
# "column_running": [[10, 2], [10, 5]],
# "row_totals": [12, 3],
# "column_totals": [10, 5],
# "grand_total": 15,
# }
Walk-through: Grouping by "Size" on rows and "Date" on columns combines "L" sales on "2025-04-01" across stores and colors (6 + 4 = 10), leaves ("S", "2025-04-01") as 0, and produces grand total 15.
Example 3
records = [
{"Store ID": "sea-9", "Date": "2025-05-01", "Color": "coral", "Size": "XL", "Shirts sold": 0},
{"Store ID": "sea-9", "Date": "2025-05-02", "Color": "ivory", "Size": "M", "Shirts sold": 7},
]
build_pivot_table(records, "Color", "Size", "Shirts sold")
# Output:
# {
# "rows": ["coral", "ivory"],
# "columns": ["XL", "M"],
# "values": [[0, 0], [0, 7]],
# "row_running": [[0, 0], [0, 7]],
# "column_running": [[0, 0], [0, 7]],
# "row_totals": [0, 7],
# "column_totals": [0, 7],
# "grand_total": 7,
# }
Walk-through: Even though "coral" / "XL" has 0 shirts sold, both "coral" and "XL" still appear on their respective axes in first-appearance order.
Constraints
0 <= len(records) <= 10^5- Every record in
recordscontainsrow_field,column_field, andvalue_field. - Axis label values (
record[row_field]andrecord[column_field]) are hashable scalars (such asstrorint), andrecord[value_field]is anintorfloat(which may be0, positive, or negative for returns). - Target time complexity is
O(n + R * C), wheren = len(records),R = len(rows), andC = len(columns).
Step-by-step walkthrough
Understand the goal and output contract
A pivot table summarizes a flat list of dictionary records as a 2D matrix: one chosen key labels the rows (vertical axis), a second chosen key labels the columns (horizontal axis), and each cell
(r, c)holds the sum of a numeric metric across all records sharing both labels.Raw records (Example 2): Pivoted by Size (rows) x Date (columns): L, 2025-04-01, 6 2025-04-01 2025-04-02 | Row Total S, 2025-04-02, 3 --- group & sum ---> L 10 2 | 12 L, 2025-04-01, 4 S 0 3 | 3 L, 2025-04-02, 2 ------------------------------+---------- Col Tot 10 5 | 15build_pivot_table(records, row_field, column_field, value_field)returns an eight-key dictionary while delegating to an object-orientedPivotTableclass that also supports aligned text rendering: -rowsandcolumns: distinct axis values in exact order of first appearance (in Example 1,"ny-10"appears before"la-20"and"chi-30", rather than alphabetical order). -values: rectangularR x Cgrid of summed quantities, filling unseen(row, column)combinations with0. -row_running:R x Ccumulative prefix sums moving left to right across each row. -column_running:R x Ccumulative prefix sums moving top to bottom down each column. -row_totals,column_totals, andgrand_total: per-row sums, per-column sums, and overall sum.Why scanning per cell is too slow — accumulate in one pass
A naive approach discovers the
Rrow labels andCcolumn labels first, and then loops through allnrecords once for every(row, column)cell. That costsO(R * C * n)time — with1,000stores,30dates, and100,000records, that would execute3 * 10^9checks!Instead, every record belongs to one specific
(row_label, col_label)cell, so a single pass overself.recordssuffices: 1. Record labels on first sight: Pair arowslist with aseen_rowsset (andcolumnswithseen_columns). Membership checks takeO(1)average time, and appending only on the first encounter preserves exact appearance order. 2. Sum into a tuple-keyed map: Addrecord[value_field]intocell_sums[(row_label, col_label)]inO(1)average time. 3. Materialize the denseR x Cmatrix: Nested loops overrowsandcolumnslook upcell_sums.get((row_label, col_label), 0), guaranteeing every row hasCcolumns with0for absent combinations.Part 1: Build the `PivotTable` class and core `pivot` method
PivotTable.__init__stores a shallow list copylist(records)so external list mutations cannot alter stored data, whilepivotacceptsrow_field,column_field, andvalue_fielddynamically rather than hard-coding specific field names.class PivotTable: """Stores sales records and builds 2D pivot tables with running and grand totals.""" def __init__(self, records: List[Dict[str, object]]): # Shallow-copy the list so later appends/pops by the caller do not alter stored records. self.records = list(records) def pivot( self, row_field: str, column_field: str, value_field: str ) -> Tuple[List[object], List[object], List[List[float]]]: """Group by (row_field, column_field) and sum value_field in first-appearance order.""" # rows, columns: distinct axis labels in exact order of first appearance rows = [] columns = [] # seen_rows, seen_columns: sets for O(1) duplicate checks while building rows/columns seen_rows = set() seen_columns = set() # cell_sums: dict mapping (row_label, col_label) -> accumulated sum, e.g. ("ny-10", "navy"): 20 cell_sums = {} # Phase 1: Scan records once to record label order and accumulate per-cell sums. for record in self.records: row_label = record[row_field] col_label = record[column_field] if row_label not in seen_rows: seen_rows.add(row_label) rows.append(row_label) if col_label not in seen_columns: seen_columns.add(col_label) columns.append(col_label) cell_key = (row_label, col_label) cell_sums[cell_key] = cell_sums.get(cell_key, 0) + record[value_field] # Phase 2: Materialize a rectangular R x C grid, filling unseen (row, col) pairs with 0. values = [] for row_label in rows: grid_row = [] for col_label in columns: grid_row.append(cell_sums.get((row_label, col_label), 0)) values.append(grid_row) return rows, columns, valuesPart 2: Compute running totals along both axes
Once
valuesis built, we derive every cumulative grid and summary total directly fromvaluesinO(R * C)time without touchingself.recordsagain:values (Example 1, top 2 rows): row_running (left -> right): column_running (top -> bottom): [ 20, 5, 0 ] [ 20, 20+5=25, 25+0=25 ] [ 20, 5, 0 ] [ 4, 0, 15 ] [ 4, 4+0=4, 4+15=19 ] [ 20+4=24, 5+0=5, 0+15=15 ]running_across_rows: Resetrunning_sum = 0at the start of each row and accumulate across columns from left to right.running_down_columns: For cell(row_idx, col_idx), take the cumulative total right above it (col_running[row_idx - 1][col_idx], or0on row0) and addvalues[row_idx][col_idx].
def running_across_rows(values: List[List[float]]) -> List[List[float]]: """Compute cumulative prefix sums from left to right across every row.""" # row_running: R x C grid where entry [r][c] = sum(values[r][0 .. c]) row_running = [] for row_values in values: running_sum = 0 running_row = [] for cell_value in row_values: running_sum += cell_value running_row.append(running_sum) row_running.append(running_row) return row_running def running_down_columns(values: List[List[float]]) -> List[List[float]]: """Compute cumulative prefix sums from top to bottom down every column.""" # col_running: R x C grid where entry [r][c] = sum(values[0 .. r][c]) col_running = [] for row_idx in range(len(values)): running_row = [] for col_idx in range(len(values[row_idx])): # Row 0 has no cells above it, so its prefix starts at 0. above_sum = col_running[row_idx - 1][col_idx] if row_idx > 0 else 0 running_row.append(above_sum + values[row_idx][col_idx]) col_running.append(running_row) return col_runningDerive grand totals from the running grids
The summary totals sit directly at the edges of the two running grids: - Each row's total is the final element of its
row_runningrow (running_row[-1]). - The column totals list is a copy of the final row ofcolumn_running(list(column_running[-1]), or[]whenrecordsis empty). -grand_totalissum(row_totals)(0when empty, and always equal tosum(column_totals)).with_totalsbuilds onself.pivot(...)without repeating any grouping code, andbuild_pivot_tabledelegates straight toPivotTable(records).with_totals(...):def with_totals( self, row_field: str, column_field: str, value_field: str ) -> Dict[str, object]: """Build the pivot grid and derive running totals and grand totals directly from it.""" rows, columns, values = self.pivot(row_field, column_field, value_field) row_running = running_across_rows(values) column_running = running_down_columns(values) # Read row totals from the rightmost column of row_running so cells and totals always match. row_totals = [] for running_row in row_running: row_totals.append(running_row[-1] if running_row else 0) # Read column totals from the bottom row of column_running (empty if there are 0 records). column_totals = list(column_running[-1]) if column_running else [] 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": sum(row_totals), } def build_pivot_table( records: List[Dict[str, object]], row_field: str, column_field: str, value_field: str, ) -> Dict[str, object]: return PivotTable(records).with_totals(row_field, column_field, value_field)Render an aligned text table and trace Example 1
Separating numeric calculation (
with_totals) from string presentation (render) keeps unit testing exact while letting callers print clean reports.renderconverts the requested view ("values","row_running", or"column_running") plus optional"Total"borders into a 2D list of strings, andformat_text_tablemeasures each column's maximum character width so column0is left-aligned (.ljust) and columns1..Nare right-aligned (.rjust).def format_text_table(cells: List[List[str]]) -> str: """Align a 2D table of strings: row labels left-aligned, numeric columns right-aligned.""" if not cells: return "" # widths[col_idx]: maximum string length appearing in column col_idx across all rows widths = [0] * len(cells[0]) for line in cells: for col_idx in range(len(line)): if len(line[col_idx]) > widths[col_idx]: widths[col_idx] = len(line[col_idx]) formatted_lines = [] for line in cells: # Left-align column 0 (text labels) and right-align columns 1..N (numbers/headers). aligned_cells = [line[0].ljust(widths[0])] for col_idx in range(1, len(line)): aligned_cells.append(line[col_idx].rjust(widths[col_idx])) formatted_lines.append(" ".join(aligned_cells)) return "\n".join(formatted_lines)Tracing Example 1 (
row_field="Store ID",column_field="Color",value_field="Shirts sold"):Pass 1 (first-appearance labels & non-zero cell_sums): rows = ['ny-10', 'la-20', 'chi-30'] columns = ['navy', 'white', 'olive'] ('ny-10', 'navy'): 12 + 8 = 20 ('la-20', 'olive'): 15 ('ny-10', 'white'): 5 ('la-20', 'navy'): 4 ('chi-30', 'white'): 9 Rendered output from render("Store ID", "Color", "Shirts sold"): Store ID / Color navy white olive Total ny-10 20 5 0 25 la-20 4 0 15 19 chi-30 0 9 0 9 Total 24 14 15 53Notice that
sum(row_totals) = 25 + 19 + 9 = 53andsum(column_totals) = 24 + 14 + 15 = 53agree identically.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def running_across_rows(values: List[List[float]]) -> List[List[float]]: """Compute cumulative prefix sums from left to right across every row.""" # row_running: R x C grid where entry [r][c] = sum(values[r][0 .. c]) row_running = [] for row_values in values: running_sum = 0 running_row = [] for cell_value in row_values: running_sum += cell_value running_row.append(running_sum) row_running.append(running_row) return row_running def running_down_columns(values: List[List[float]]) -> List[List[float]]: """Compute cumulative prefix sums from top to bottom down every column.""" # col_running: R x C grid where entry [r][c] = sum(values[0 .. r][c]) col_running = [] for row_idx in range(len(values)): running_row = [] for col_idx in range(len(values[row_idx])): # Row 0 has no cells above it, so its prefix starts at 0. above_sum = col_running[row_idx - 1][col_idx] if row_idx > 0 else 0 running_row.append(above_sum + values[row_idx][col_idx]) col_running.append(running_row) return col_running def format_text_table(cells: List[List[str]]) -> str: """Align a 2D table of strings: row labels left-aligned, numeric columns right-aligned.""" if not cells: return "" # widths[col_idx]: maximum string length appearing in column col_idx across all rows widths = [0] * len(cells[0]) for line in cells: for col_idx in range(len(line)): if len(line[col_idx]) > widths[col_idx]: widths[col_idx] = len(line[col_idx]) formatted_lines = [] for line in cells: # Left-align column 0 (text labels) and right-align columns 1..N (numbers/headers). aligned_cells = [line[0].ljust(widths[0])] for col_idx in range(1, len(line)): aligned_cells.append(line[col_idx].rjust(widths[col_idx])) formatted_lines.append(" ".join(aligned_cells)) return "\n".join(formatted_lines) class PivotTable: """Stores sales records and builds 2D pivot tables with running and grand totals.""" def __init__(self, records: List[Dict[str, object]]): # Shallow-copy the list so later appends/pops by the caller do not alter stored records. self.records = list(records) def pivot( self, row_field: str, column_field: str, value_field: str ) -> Tuple[List[object], List[object], List[List[float]]]: """Group by (row_field, column_field) and sum value_field in first-appearance order.""" # rows, columns: distinct axis labels in exact order of first appearance rows = [] columns = [] # seen_rows, seen_columns: sets for O(1) duplicate checks while building rows/columns seen_rows = set() seen_columns = set() # cell_sums: dict mapping (row_label, col_label) -> accumulated sum, e.g. ("ny-10", "navy"): 20 cell_sums = {} # Phase 1: Scan records once to record label order and accumulate per-cell sums. for record in self.records: row_label = record[row_field] col_label = record[column_field] if row_label not in seen_rows: seen_rows.add(row_label) rows.append(row_label) if col_label not in seen_columns: seen_columns.add(col_label) columns.append(col_label) cell_key = (row_label, col_label) cell_sums[cell_key] = cell_sums.get(cell_key, 0) + record[value_field] # Phase 2: Materialize a rectangular R x C grid, filling unseen (row, col) pairs with 0. values = [] for row_label in rows: grid_row = [] for col_label in columns: grid_row.append(cell_sums.get((row_label, col_label), 0)) values.append(grid_row) return rows, columns, values def with_totals( self, row_field: str, column_field: str, value_field: str ) -> Dict[str, object]: """Build the pivot grid and derive running totals and grand totals directly from it.""" rows, columns, values = self.pivot(row_field, column_field, value_field) row_running = running_across_rows(values) column_running = running_down_columns(values) # Read row totals from the rightmost column of row_running so cells and totals always match. row_totals = [] for running_row in row_running: row_totals.append(running_row[-1] if running_row else 0) # Read column totals from the bottom row of column_running (empty if there are 0 records). column_totals = list(column_running[-1]) if column_running else [] 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": sum(row_totals), } def render( self, row_field: str, column_field: str, value_field: str, view: str = "values", show_totals: bool = True, ) -> str: """Render one grid view ('values', 'row_running', or 'column_running') as aligned text.""" if view not in ("values", "row_running", "column_running"): raise ValueError(f"Unsupported view: {view!r}") table = self.with_totals(row_field, column_field, value_field) header = [f"{row_field} / {column_field}"] for col_label in table["columns"]: header.append(str(col_label)) if show_totals: header.append("Total") lines = [header] for row_idx in range(len(table["rows"])): line = [str(table["rows"][row_idx])] for cell_value in table[view][row_idx]: line.append(str(cell_value)) if show_totals: line.append(str(table["row_totals"][row_idx])) lines.append(line) if show_totals: total_line = ["Total"] for col_total in table["column_totals"]: total_line.append(str(col_total)) total_line.append(str(table["grand_total"])) lines.append(total_line) return format_text_table(lines) def build_pivot_table( records: List[Dict[str, object]], row_field: str, column_field: str, value_field: str, ) -> Dict[str, object]: return PivotTable(records).with_totals(row_field, column_field, value_field) if __name__ == "__main__": demo = PivotTable( [ {"Store ID": "bos-1", "Date": "2025-04-01", "Color": "grey", "Size": "L", "Shirts sold": 6}, {"Store ID": "bos-2", "Date": "2025-04-02", "Color": "teal", "Size": "S", "Shirts sold": 3}, {"Store ID": "bos-1", "Date": "2025-04-01", "Color": "teal", "Size": "L", "Shirts sold": 4}, {"Store ID": "bos-2", "Date": "2025-04-02", "Color": "grey", "Size": "L", "Shirts sold": 2}, ] ) print(demo.render("Size", "Date", "Shirts sold"))✅ Submit now — all tests should pass.
Intuition & how it works
Imagine sorting a shoebox of paper retail receipts onto a wall chart where each row is a shirt size and each column is a sale date. Instead of rummaging through the entire shoebox from top to bottom for every single square on the wall chart, you pick up each receipt once, inspect its row key and column key, and add its shirt count onto a tally pad for (row_key, col_key). Once the shoebox is empty, you copy those tallies onto the rectangular grid (writing 0 in any square that received no receipts) and sweep across rows and down columns to fill in running totals (also called prefix sums, meaning each position holds the cumulative total of all cells from the start of that row or column up to that cell) and grand totals. That 2D cross-tabulation summary is called a pivot table.
Why does the naive approach fall short? Scanning all n records separately for each (row, column) square takes O(R * C * n) time, wasting nearly all of its effort checking records that belong to other squares. Worse, re-scanning the raw records separately to compute row, column, and grand totals duplicates grouping logic and risks totals that disagree with the grid as soon as a filter or custom reducer is introduced.
Let's walk through Example 2 (Size on rows, Date on columns) over 4 records: ("L", "2025-04-01", 6), ("S", "2025-04-02", 3), ("L", "2025-04-01", 4), ("L", "2025-04-02", 2):
1. Single pass over records:
rows = ['L', 'S'] (first-appearance order)
columns = ['2025-04-01', '2025-04-02'] (first-appearance order)
cell_sums = {('L', '2025-04-01'): 10, ('S', '2025-04-02'): 3, ('L', '2025-04-02'): 2}
2. Dense 2x2 grid (unseen ('S', '2025-04-01') defaults to 0):
values = [[10, 2],
[ 0, 3]]
3. Running & grand totals derived directly from `values`:
row_running = [[10, 12], -> row_totals = [12, 3]
[ 0, 3]]
column_running = [[10, 2], -> column_totals = [10, 5]
[10, 5]] -> grand_total = 12 + 3 = 15
Complexity
Let n be the number of input records, R be the number of distinct values of row_field, and C be the number of distinct values of column_field.
- Time:
O(n + R * C). During the single pass overself.records, checkingseen_rows/seen_columnsand updatingcell_sums[(row_label, col_label)]each doO(1)average hash-table work per record, totalingO(n). Building theR x Cgridvalues, computingrow_runningandcolumn_running, and extractingrow_totals,column_totals, andgrand_totaleach visit theR * Cgrid cells a constant number of times. - Space:
O(n + R * C).self.recordsstoresndictionary references,cell_sumsstores at mostmin(n, R * C)non-empty(row, column)entries, and the output holds threeR x Cgrids (values,row_running,column_running) plusO(R + C)label and total lists.
Edge cases
- Empty input (
records = []):rows,columns,values,row_running,column_running,row_totals, andcolumn_totalsare all[], andgrand_totalis0. - Unseen
(row, column)combinations: Filled with0viacell_sums.get((row_label, col_label), 0), keeping every row length equal toCso columns stay aligned. - Records whose value is
0(Example 3): Because labels are recorded before addingrecord[value_field], zero-quantity records still register their row and column labels and produce0-filled cells. - Same field on both axes (
row_field == column_field): Produces a square diagonal matrix where off-diagonal cells are0and diagonal cells hold per-label sums. - Single row (
R = 1) or single column (C = 1):column_runningmatchesvalueswhenR = 1, androw_runningmatchesvalueswhenC = 1. - Floating-point or negative values (such as revenue or returned items): Both accumulate naturally; with floating-point inputs,
sum(row_totals)andsum(column_totals)can differ by tiny10^-15rounding noise because floating-point addition is not associative. - Missing field or non-numeric value: Raises
KeyErrororTypeErrorimmediately rather than silently dropping malformed records from totals.
Common mistakes
- Sorting row or column labels alphabetically: Example 1 expects
['ny-10', 'la-20', 'chi-30']because'ny-10'appears first inrecords. Iterating over a Pythonsetscrambles label order arbitrarily; pair a list with aset(or rely ondictinsertion order) instead. - Producing ragged rows: Emitting only cells present in
cell_sumsgives rows of unequal length, breaking both column indexing and text alignment. - Allocating the 2D grid with
[[0] * C] * R: That createsRreferences to the exact same inner list, so updating one cell overwrites the entire column. Always build a fresh inner list per row. - Re-scanning
self.recordsseparately for totals: Besides doing redundantO(n)passes, any later filter or cell-level transformation can leave totals out of sync with the grid. Always compute totals fromvalues. - Mixing calculation with
print(...): Printing insidepivot()makes unit testing clumsy and prevents callers from reusing the numeric structure. Keeppivot/with_totalspure data methods and isolate formatting insiderender.
Follow-up questions
-
How would you generalize the class so callers can group by composite multi-field axes (for instance, pairing store and date on each row)? Accept
row_fieldsas a sequence of field names and represent each composite row label as an immutable tuple, such asrow_key = tuple(record[field] for field in row_fields)(for example("ny-10", "2025-03-10")). Because Python tuples are hashable,seen_rowsandcell_sums[(row_key, col_key)]continue to run inO(1)average time with zero changes to the grid or running-total logic. Inrender, format tuple labels either by joining segments ("ny-10 | 2025-03-10") or by emitting one label column per row field. -
How would you redesign cell accumulation to support reducers like count, mean, or max while keeping row and grand summaries mathematically accurate? Store a small accumulator state per
(row_label, col_label)cell instead of a single scalar — for instance[count, total, current_max]— and compute row, column, and grand summaries by merging those states rather than averaging already-averaged cells. That distinction is essential for means: a row's true mean isrow_total / row_count, not the unweighted average of its cell means (which would weight a 1-shirt cell equally with a 500-shirt cell). Likewise, running views generalize to prefix merges of the accumulator state across a row or down a column. -
If the input log grows too large to hold in RAM at once, how can you still build the exact same pivot summary? Observe that
pivot()needs only a single sequential scan over the input and retains onlyseen_rows,seen_columns, andcell_sumsin memory. Replaceself.records = list(records)with a streaming source (an iterable factory or database cursor that yields one record at a time without buffering raw records), dropping memory fromO(n + R * C)toO(R * C). If evenR * Cexceeds single-host RAM, pushSELECT row_field, column_field, SUM(value_field) ... GROUP BY row_field, column_fielddown to a columnar warehouse or partition records by hashing(row_label, col_label)across workers in a map-reduce pipeline (a distributed two-phase pattern where mappers emit((row, col), qty)pairs and reducers sum each key). -
How would you let callers restrict a pivot query to a subset of records (such as one specific date) without modifying
__init__? Add an optionalfilters: Optional[Dict[str, object]] = None(or callable predicate) parameter topivot,with_totals, andrender, and skip non-matching records at the top of thefor record in self.records:loop. Becausewith_totalsandrenderderive every cumulative sum and grand total strictly frompivot's grid, filtering in that single place keeps cells and totals automatically consistent. Clarify with the interviewer whether stores or colors excluded by the filter should be omitted from the axes or retained as all-zero rows/columns.
python
def record_matches(record: Dict[str, object], filters: Optional[Dict[str, object]]) -> bool:
if not filters:
return True
for field_name, expected_value in filters.items():
if record.get(field_name) != expected_value:
return False
return True
Follow-up questions
- How would you generalize the class so callers can group by composite multi-field axes (for instance, pairing store and date on each row)?
- How would you redesign cell accumulation to support reducers like count, mean, or max while keeping row and grand summaries mathematically accurate?
- If the input log grows too large to hold in RAM at once, how can you still build the exact same pivot summary?
- How would you let callers restrict a pivot query to a subset of records (such as one specific date) without modifying `__init__`?
Similar questions
- Nested Pivot Table Cell Aggregator
- Boolean AST Evaluation with Short-Circuiting
- Multi-Column Pivot Table Aggregator
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination