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

  1. Dynamic Field Selection: row_field defines the vertical (y-axis) grouping key, column_field defines the horizontal (x-axis) grouping key, and value_field names the numeric quantity summed inside each (row, column) cell. Field names must be matched verbatim (preserving spaces and letter case).
  2. 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 scanning records from index 0 onward—do not sort them alphabetically. Even a record whose numeric value is 0 registers its row and column labels.
  3. 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 value 0.
  4. Cumulative Running Grids: Computed in the displayed axis order directly from values:
    • row_running: an R x C grid where entry [r][c] equals sum(values[r][0 : c + 1]) (accumulating left to right across each row).
    • column_running: an R x C grid where entry [r][c] equals sum(values[0 : r + 1][c]) (accumulating top to bottom down each column).
  5. Summary Totals:
    • row_totals: length-R list where entry r sums row r across all columns.
    • column_totals: length-C list where entry c sums column c across all rows.
    • grand_total: overall sum across all cells (0 when records is empty), guaranteed to equal both sum(row_totals) and sum(column_totals).
  6. Return Payload & Immutability: build_pivot_table returns a dictionary with keys "rows", "columns", "values", "row_running", "column_running", "row_totals", "column_totals", and "grand_total", without mutating the caller's records. PivotTable.render formats 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 records contains row_field, column_field, and value_field.
  • Axis label values (record[row_field] and record[column_field]) are hashable scalars (such as str or int), and record[value_field] is an int or float (which may be 0, positive, or negative for returns).
  • Target time complexity is O(n + R * C), where n = len(records), R = len(rows), and C = len(columns).

Step-by-step walkthrough

  1. 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 |    15
    

    build_pivot_table(records, row_field, column_field, value_field) returns an eight-key dictionary while delegating to an object-oriented PivotTable class that also supports aligned text rendering: - rows and columns: 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: rectangular R x C grid of summed quantities, filling unseen (row, column) combinations with 0. - row_running: R x C cumulative prefix sums moving left to right across each row. - column_running: R x C cumulative prefix sums moving top to bottom down each column. - row_totals, column_totals, and grand_total: per-row sums, per-column sums, and overall sum.

  2. Why scanning per cell is too slow — accumulate in one pass

    A naive approach discovers the R row labels and C column labels first, and then loops through all n records once for every (row, column) cell. That costs O(R * C * n) time — with 1,000 stores, 30 dates, and 100,000 records, that would execute 3 * 10^9 checks!

    Instead, every record belongs to one specific (row_label, col_label) cell, so a single pass over self.records suffices: 1. Record labels on first sight: Pair a rows list with a seen_rows set (and columns with seen_columns). Membership checks take O(1) average time, and appending only on the first encounter preserves exact appearance order. 2. Sum into a tuple-keyed map: Add record[value_field] into cell_sums[(row_label, col_label)] in O(1) average time. 3. Materialize the dense R x C matrix: Nested loops over rows and columns look up cell_sums.get((row_label, col_label), 0), guaranteeing every row has C columns with 0 for absent combinations.

  3. Part 1: Build the `PivotTable` class and core `pivot` method

    PivotTable.__init__ stores a shallow list copy list(records) so external list mutations cannot alter stored data, while pivot accepts row_field, column_field, and value_field dynamically 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, values
    
  4. Part 2: Compute running totals along both axes

    Once values is built, we derive every cumulative grid and summary total directly from values in O(R * C) time without touching self.records again:

    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: Reset running_sum = 0 at 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], or 0 on row 0) and add values[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_running
    
  5. Derive 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_running row (running_row[-1]). - The column totals list is a copy of the final row of column_running (list(column_running[-1]), or [] when records is empty). - grand_total is sum(row_totals) (0 when empty, and always equal to sum(column_totals)).

    with_totals builds on self.pivot(...) without repeating any grouping code, and build_pivot_table delegates straight to PivotTable(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)
    
  6. 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. render converts the requested view ("values", "row_running", or "column_running") plus optional "Total" borders into a 2D list of strings, and format_text_table measures each column's maximum character width so column 0 is left-aligned (.ljust) and columns 1..N are 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     53
    

    Notice that sum(row_totals) = 25 + 19 + 9 = 53 and sum(column_totals) = 24 + 14 + 15 = 53 agree identically.

  7. 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 over self.records, checking seen_rows / seen_columns and updating cell_sums[(row_label, col_label)] each do O(1) average hash-table work per record, totaling O(n). Building the R x C grid values, computing row_running and column_running, and extracting row_totals, column_totals, and grand_total each visit the R * C grid cells a constant number of times.
  • Space: O(n + R * C). self.records stores n dictionary references, cell_sums stores at most min(n, R * C) non-empty (row, column) entries, and the output holds three R x C grids (values, row_running, column_running) plus O(R + C) label and total lists.

Edge cases

  • Empty input (records = []): rows, columns, values, row_running, column_running, row_totals, and column_totals are all [], and grand_total is 0.
  • Unseen (row, column) combinations: Filled with 0 via cell_sums.get((row_label, col_label), 0), keeping every row length equal to C so columns stay aligned.
  • Records whose value is 0 (Example 3): Because labels are recorded before adding record[value_field], zero-quantity records still register their row and column labels and produce 0-filled cells.
  • Same field on both axes (row_field == column_field): Produces a square diagonal matrix where off-diagonal cells are 0 and diagonal cells hold per-label sums.
  • Single row (R = 1) or single column (C = 1): column_running matches values when R = 1, and row_running matches values when C = 1.
  • Floating-point or negative values (such as revenue or returned items): Both accumulate naturally; with floating-point inputs, sum(row_totals) and sum(column_totals) can differ by tiny 10^-15 rounding noise because floating-point addition is not associative.
  • Missing field or non-numeric value: Raises KeyError or TypeError immediately 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 in records. Iterating over a Python set scrambles label order arbitrarily; pair a list with a set (or rely on dict insertion order) instead.
  • Producing ragged rows: Emitting only cells present in cell_sums gives rows of unequal length, breaking both column indexing and text alignment.
  • Allocating the 2D grid with [[0] * C] * R: That creates R references 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.records separately for totals: Besides doing redundant O(n) passes, any later filter or cell-level transformation can leave totals out of sync with the grid. Always compute totals from values.
  • Mixing calculation with print(...): Printing inside pivot() makes unit testing clumsy and prevents callers from reusing the numeric structure. Keep pivot / with_totals pure data methods and isolate formatting inside render.

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_fields as a sequence of field names and represent each composite row label as an immutable tuple, such as row_key = tuple(record[field] for field in row_fields) (for example ("ny-10", "2025-03-10")). Because Python tuples are hashable, seen_rows and cell_sums[(row_key, col_key)] continue to run in O(1) average time with zero changes to the grid or running-total logic. In render, 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 is row_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 only seen_rows, seen_columns, and cell_sums in memory. Replace self.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 from O(n + R * C) to O(R * C). If even R * C exceeds single-host RAM, push SELECT row_field, column_field, SUM(value_field) ... GROUP BY row_field, column_field down 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 optional filters: Optional[Dict[str, object]] = None (or callable predicate) parameter to pivot, with_totals, and render, and skip non-matching records at the top of the for record in self.records: loop. Because with_totals and render derive every cumulative sum and grand total strictly from pivot'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

Similar questions

More Sigmacomputing interview questions

All 4 Sigmacomputing questions →