Nested Pivot Table Cell Aggregator

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Write build_pivot_table, a function that summarizes flat (row_key, column_key, value) records into a two-dimensional lookup dictionary:

def build_pivot_table(
    records: List[List],
    aggregation: str = "sum",
) -> Dict[str, Dict[str, float]]:

Each element in records is a 3-item list or tuple [row_key, column_key, value], where row_key and column_key are strings and value is a real number (int or float).

Your implementation must satisfy these rules:

  1. Nested O(1) lookup structure: Group records sharing the same (row_key, column_key) pair and return a nested dictionary table where table[row_key][column_key] holds that cell's aggregated metric.
  2. Supported aggregation modes: Support aggregation values "sum" (default), "average" (arithmetic mean using true floating-point division), and "minimum" (smallest value observed in that cell). Raise ValueError whenever aggregation is any other string, even if records is empty.
  3. Sparse cell representation: Populate only (row_key, column_key) combinations that actually occur in records. Never insert 0 placeholders for missing row/column pairs; an empty records list returns {}.
  4. Constant-space per-cell state: Rather than appending every raw number into per-cell lists, maintain a fixed-size intermediate summary per cell (total, count, and minimum) in a single streaming pass so memory scales with the number of distinct populated cells rather than total record count.

Examples

Example 1

Input:
  records = [
      ["north", "web", 12],
      ["north", "web", 18],
      ["north", "retail", 9],
      ["south", "web", 14],
  ]
  aggregation = "sum"  # default

Output:
  {"north": {"web": 30, "retail": 9}, "south": {"web": 14}}

Explanation: Cell ("north", "web") combines 12 + 18 = 30, while ("north", "retail") and ("south", "web") each have one record. Because "south" has no "retail" records, "retail" is omitted under "south".

Example 2

Input:
  records = [
      ["north", "web", 12],
      ["north", "web", 18],
      ["north", "retail", 9],
      ["south", "web", 14],
  ]
  aggregation = "average"

Output:
  {"north": {"web": 15.0, "retail": 9.0}, "south": {"web": 14.0}}

Explanation: Cell ("north", "web") tracks total = 30 across count = 2 records, dividing 30 / 2 = 15.0. Single-record cells divide their value by 1.

Example 3

Input:
  records = [
      ["north", "web", 12],
      ["north", "web", 18],
      ["north", "retail", 9],
      ["south", "web", 14],
  ]
  aggregation = "minimum"

Output:
  {"north": {"web": 12, "retail": 9}, "south": {"web": 14}}

Explanation: Cell ("north", "web") seeds its running minimum from its first observation 12 and compares 18, retaining 12.

Constraints

  • 0 <= len(records) <= 10^5
  • Every item of records is a 3-element list or tuple (row_key, column_key, value) with non-empty string keys and numeric value (-10^9 <= value <= 10^9).
  • aggregation is expected to be "sum", "average", or "minimum" (raise ValueError otherwise).
  • Time complexity must be O(N) expected for N = len(records), and space complexity must be O(C) for C distinct (row_key, column_key) pairs.

Step-by-step walkthrough

  1. Understand the goal and lookup structure

    A pivot table condenses a flat sequence of [row_key, column_key, value] records by routing every observation with the same (row_key, column_key) pair into one cell and reducing its numbers with a chosen rule ("sum", "average", or "minimum").

    To deliver instant lookup by row key and column key, we return a two-level nested dictionary pivot_table[row_key][column_key] -> number:

    Input records:                        Nested lookup dictionary (for "sum"):
      ["north", "web", 12]                  {
      ["north", "web", 18]   ----------->     "north": {"web": 30, "retail": 9},
      ["north", "retail", 9]                  "south": {"web": 14}
      ["south", "web", 14]                  }
    

    Two rules govern the output shape: - Fast O(1) lookup: Reading pivot_table["north"]["web"] executes two hash-table lookups in constant expected time regardless of table dimensions. - Sparse cells: Only (row_key, column_key) pairs present in records appear in the dictionary. For instance, "south" omits "retail" because no ("south", "retail") record occurred—padding unseen cells with 0 would conflate "no observations" with "observations summing to 0" (and the average or minimum of zero records is undefined).

  2. Why buffering raw lists per cell wastes memory

    A first attempt might append every incoming number into groups[row_key][column_key] as a list, then run sum(values), sum(values) / len(values), or min(values) at the end.

    Although that runs in O(N) time across N records, it retains all N numbers in RAM. When 10 million order records collapse into 20 (region, channel) cells, keeping 10 million list entries wastes megabytes of memory when each cell only needs a tiny running summary.

  3. Design the `O(1)` intermediate state per cell

    Ask: what minimal state inside each cell lets us incorporate a newly arriving value without re-examining earlier records?

    • For sum, track total: each arriving value updates total += value.
    • For average, a running mean by itself is insufficient! Knowing only that a cell's current mean is 15 does not tell you how heavily to weight a new 6: one prior value gives (15 + 6) / 2 = 10.5, whereas two prior values give (12 + 18 + 6) / 3 = 12.0. Tracking both total and count solves this cleanly: update total += value and count += 1, then divide total / count once during finalization.
    • For minimum, neither total nor count reveals the smallest number seen, so track minimum and update it whenever value < minimum. Always seed minimum with the cell's first value, never 0—otherwise a cell receiving [12, 18] would wrongly report 0.

    Keeping all three fields (total, count, minimum) in one compact dictionary per cell uses O(1) space per cell and lets one accumulation loop serve all three modes:

    VALID_AGGREGATIONS = ("sum", "average", "minimum")
    
    
    def create_cell_state(first_value: float) -> Dict[str, Any]:
        """Initialize the O(1) running summary for a cell from its first seen value."""
        # Initialize "minimum" to first_value (never 0!), otherwise all-positive cells would report 0.
        return {
            "total": first_value,
            "count": 1,
            "minimum": first_value,
        }
    
    
    def update_cell_state(state: Dict[str, Any], value: float) -> None:
        """Fold one more numeric value into an existing cell's running summary."""
        # Maintaining both "total" and "count" lets us compute exact averages in O(1) space.
        state["total"] += value
        state["count"] += 1
        if value < state["minimum"]:
            state["minimum"] = value
    
    
    def finalize_cell(state: Dict[str, Any], aggregation: str) -> float:
        """Convert a cell's intermediate state into the requested final metric."""
        if aggregation == "sum":
            return state["total"]
        if aggregation == "average":
            # True division (/) ensures e.g. 3 / 2 produces 1.5 rather than integer 1.
            return state["total"] / state["count"]
        return state["minimum"]
    
  4. Build the pivot table in two clean passes

    With our state helpers in place, build_pivot_table separates cleanly into two passes:

    1. Pass 1 (Accumulate): Validate aggregation upfront (raising ValueError immediately on unknown names like "avg", even when records is empty). Stream through records once and update cell_states[row_key][column_key].
    2. Pass 2 (Finalize): Walk cell_states and construct pivot_table[row_key][column_key] = finalize_cell(state, aggregation).

    Keeping cell_states separate from pivot_table ensures internal state dictionaries never leak into the output, and in a larger analytics engine the same cell_states can answer "sum", "average", and "minimum" queries without re-scanning raw records.

  5. Trace the examples across all three modes

    Trace records = [["north", "web", 12], ["north", "web", 18], ["north", "retail", 9], ["south", "web", 14]]:

    Step  Record                   Cell            Action  State after step {total, count, minimum}
    ----  -----------------------  --------------  ------  ----------------------------------------
    1     ["north", "web", 12]     north / web     create  {total: 12, count: 1, minimum: 12}
    2     ["north", "web", 18]     north / web     update  {total: 30, count: 2, minimum: 12}
    3     ["north", "retail", 9]   north / retail  create  {total:  9, count: 1, minimum:  9}
    4     ["south", "web", 14]     south / web     create  {total: 14, count: 1, minimum: 14}
    
    Finalize pass:
      - "sum"     -> north/web: 30,          north/retail: 9,     south/web: 14
      - "average" -> north/web: 30/2 = 15.0, north/retail: 9/1,   south/web: 14/1
      - "minimum" -> north/web: 12,          north/retail: 9,     south/web: 14
    

    All three examples match: {"north": {"web": 30, "retail": 9}, "south": {"web": 14}} for "sum", 15.0 on north/web for "average", and 12 on north/web for "minimum".

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    VALID_AGGREGATIONS = ("sum", "average", "minimum")
    
    
    def create_cell_state(first_value: float) -> Dict[str, Any]:
        """Initialize the O(1) running summary for a cell from its first seen value."""
        # Initialize "minimum" to first_value (never 0!), otherwise all-positive cells would report 0.
        return {
            "total": first_value,
            "count": 1,
            "minimum": first_value,
        }
    
    
    def update_cell_state(state: Dict[str, Any], value: float) -> None:
        """Fold one more numeric value into an existing cell's running summary."""
        # Maintaining both "total" and "count" lets us compute exact averages in O(1) space.
        state["total"] += value
        state["count"] += 1
        if value < state["minimum"]:
            state["minimum"] = value
    
    
    def finalize_cell(state: Dict[str, Any], aggregation: str) -> float:
        """Convert a cell's intermediate state into the requested final metric."""
        if aggregation == "sum":
            return state["total"]
        if aggregation == "average":
            # True division (/) ensures e.g. 3 / 2 produces 1.5 rather than integer 1.
            return state["total"] / state["count"]
        return state["minimum"]
    
    
    def build_pivot_table(records: List[List], aggregation: str = "sum") -> Dict[str, Dict[str, float]]:
        # Validate the aggregation name upfront so typos fail immediately, even on empty input.
        if aggregation not in VALID_AGGREGATIONS:
            raise ValueError(f"Unsupported aggregation: {aggregation!r}")
    
        # cell_states: nested dict {row_key: {column_key: {"total": ..., "count": ..., "minimum": ...}}}
        cell_states: Dict[str, Dict[str, Dict[str, Any]]] = {}
    
        # Phase 1: stream through all records and update the running state for each (row_key, column_key).
        for row_key, column_key, value in records:
            if row_key not in cell_states:
                cell_states[row_key] = {}
    
            row_cells = cell_states[row_key]
            if column_key in row_cells:
                update_cell_state(row_cells[column_key], value)
            else:
                row_cells[column_key] = create_cell_state(value)
    
        # Phase 2: build the final nested lookup dictionary {row_key: {column_key: metric}}.
        # Only observed (row_key, column_key) pairs are included; unseen pairs stay absent.
        pivot_table: Dict[str, Dict[str, float]] = {}
        for row_key, row_cells in cell_states.items():
            pivot_table[row_key] = {}
            for column_key, state in row_cells.items():
                pivot_table[row_key][column_key] = finalize_cell(state, aggregation)
    
        return pivot_table
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture sorting regional order slips into a wall of pigeonhole cubbies arranged by row ("north", "south") and column ("web", "retail"). A pivot table is that grid of cubbies: instead of scanning an unsorted stack of slips every time someone asks a question, you jump straight to row "north", column "web" and read one summarized figure. Rather than stuffing thousands of paper slips inside each cubby, you clip a tiny index card to the front of each cubby recording just three numbers: the running sum, the count of slips, and the lowest slip amount seen so far.

Scanning all N records on every (row_key, column_key) lookup would cost O(N) per query instead of constant time. Even grouping raw values into per-cell lists (groups[row][col].append(value)) wastes O(N) memory storing every raw number when millions of records land in just a few dozen cells. Worse, updating a bare running average without a count gives skewed results once a third record arrives, and initializing a running minimum to 0 wrongly reports 0 whenever every value in a cell is positive.

We represent the grid as a two-level hash map (a Python dictionary mapping keys to values in O(1) expected time) of per-cell summary dictionaries {"total", "count", "minimum"} and compute final metrics in a second pass. On [["north", "web", 12], ["north", "web", 18], ["north", "retail", 9], ["south", "web", 14]]: 1. ["north", "web", 12] initializes cell north/web to {total: 12, count: 1, minimum: 12}. 2. ["north", "web", 18] updates cell north/web to {total: 30, count: 2, minimum: 12}. 3. ["north", "retail", 9] and ["south", "web", 14] initialize north/retail ({9, 1, 9}) and south/web ({14, 1, 14}). 4. Finalizing north/web emits total = 30 for "sum", 30 / 2 = 15.0 for "average", or minimum = 12 for "minimum".

Complexity

Let N be the number of input records and C be the number of distinct (row_key, column_key) pairs observed (C <= N).

  • Time: O(N) expected. Pass 1 visits each of the N records once, performing two O(1) expected dictionary lookups and three O(1) arithmetic updates. Pass 2 visits each of the C populated cells once to finalize its metric, and since C <= N, overall runtime is O(N) expected.
  • Space: O(C). Both cell_states and the returned pivot_table hold one entry per distinct (row_key, column_key) pair, storing a fixed 3-key dictionary per cell regardless of how many records map to that cell.
  • Cell lookup: O(1) expected. Reading pivot_table[row_key][column_key] performs two hash-table lookups.

Edge cases

  • Empty records list: Returns {} for "sum", "average", and "minimum", while still raising ValueError if aggregation is invalid.
  • Single record in a cell: total and minimum equal that value, and average divides by count = 1 to return that value as a float.
  • All positive values for "minimum": Seeding "minimum" from first_value rather than 0 ensures [12, 18] returns 12 (Example 3).
  • Negative numbers and floating-point values: Handled directly by +, /, and < (for instance, [-3, 5, -10] produces sum -8, average -8/3, and minimum -10).
  • Unobserved (row_key, column_key) pairs: Omitted rather than zero-padded (e.g., "retail" is absent under "south" in Examples 1–3), distinguishing "no records" from "records summing to 0".
  • List or tuple records: Sequence unpacking for row_key, column_key, value in records: accepts both ["north", "web", 12] lists and ("north", "web", 12) tuples without mutating the input.

Common mistakes

  • Initializing minimum to 0: Any cell with strictly positive numbers (such as [12, 18]) stays stuck at 0; always seed from the cell's first value or float("inf").
  • Using floor division // instead of true division /: 3 // 2 truncates to 1, whereas the mean of [1, 2] must be 1.5.
  • Updating a running average without count: Computing avg = (avg + new_value) / 2 over-weights newer records (((12 + 18)/2 + 30)/2 = 22.5 instead of 20.0).
  • Returning collections.defaultdict directly: Reading a missing key on a defaultdict silently inserts an empty dictionary instead of raising KeyError, mutating the table during read-only lookups.
  • Silently falling back on unknown aggregation names: Without upfront validation, a typo such as "avg" hits a trailing else branch and quietly returns minimums instead of failing fast.

Alternative approaches

  • Buffer a raw value list per cell (Dict[str, Dict[str, List[float]]]): Easiest to code and runs in O(N) time, but consumes O(N) memory rather than O(C). Only needed for order-statistic metrics like exact median that cannot be compressed into O(1) numbers per cell.
  • Single-level dictionary keyed by (row_key, column_key) tuples: table[(row_key, column_key)] also gives O(1) expected cell lookup, but enumerating all columns inside one row_key then requires scanning every key in the dictionary instead of reading table[row_key].

Follow-up questions

  • Which additional metrics—such as maximum, count, variance, or exact median—can still use constant memory per cell, and which ones cannot? count is already present in our cell state, and maximum adds a single float initialized to first_value and updated whenever value > state["maximum"]. Population and sample variance also fit in O(1) space per cell by maintaining a running sum of squares alongside total and count (or Welford's online update to avoid catastrophic floating-point cancellation). Exact median, by contrast, cannot be computed in O(1) memory per cell because future arrivals can shift the middle element arbitrarily; you must either retain all cell values (e.g., in two heaps using O(N) total space) or trade exactness for bounded memory using a quantile sketch (a fixed-size summary structure such as t-digest that approximates percentiles within a small error bound).
  • How would you extend your cell states to compute accurate row summaries, column summaries, and a grand total across every aggregation mode? Never aggregate finalized cell outputs directly, because the mean of a row is not the unweighted average of its column means when cells have unequal record counts! Instead, merge the raw intermediate states (merged_total = a["total"] + b["total"], merged_count = a["count"] + b["count"], merged_min = min(a["minimum"], b["minimum"])) across every cell in a row, column, or the full table, and call finalize_cell once on each merged state.
  • If input records are partitioned across many worker nodes, how can you parallelize building the pivot table without skewing averages or minimums? An operation is associative and commutative when grouping and arrival order never alter the outcome (for example, (a + b) + c == a + (b + c) and min(min(a, b), c) == min(a, min(b, c))). Because total, count, and minimum all merge associatively and commutatively, each worker node can independently stream its shard into a local cell_states map of size O(C), send only those compact per-cell state dictionaries over the network, and let a reducer merge matching (row_key, column_key) states before running finalize_cell once at the end.

Follow-up questions

Similar questions

More Sigmacomputing interview questions

All 4 Sigmacomputing questions →