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:
- Nested
O(1)lookup structure: Group records sharing the same(row_key, column_key)pair and return a nested dictionarytablewheretable[row_key][column_key]holds that cell's aggregated metric. - Supported aggregation modes: Support
aggregationvalues"sum"(default),"average"(arithmetic mean using true floating-point division), and"minimum"(smallest value observed in that cell). RaiseValueErrorwheneveraggregationis any other string, even ifrecordsis empty. - Sparse cell representation: Populate only
(row_key, column_key)combinations that actually occur inrecords. Never insert0placeholders for missing row/column pairs; an emptyrecordslist returns{}. - 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, andminimum) 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
recordsis a 3-elementlistortuple(row_key, column_key, value)with non-empty string keys and numericvalue(-10^9 <= value <= 10^9). aggregationis expected to be"sum","average", or"minimum"(raiseValueErrorotherwise).- Time complexity must be
O(N)expected forN = len(records), and space complexity must beO(C)forCdistinct(row_key, column_key)pairs.
Step-by-step walkthrough
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: Readingpivot_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 inrecordsappear in the dictionary. For instance,"south"omits"retail"because no("south", "retail")record occurred—padding unseen cells with0would conflate "no observations" with "observations summing to 0" (and the average or minimum of zero records is undefined).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 runsum(values),sum(values) / len(values), ormin(values)at the end.Although that runs in
O(N)time acrossNrecords, it retains allNnumbers 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.Design the `O(1)` intermediate state per cell
Ask: what minimal state inside each cell lets us incorporate a newly arriving
valuewithout re-examining earlier records?- For
sum, tracktotal: each arrivingvalueupdatestotal += value. - For
average, a running mean by itself is insufficient! Knowing only that a cell's current mean is15does not tell you how heavily to weight a new6: one prior value gives(15 + 6) / 2 = 10.5, whereas two prior values give(12 + 18 + 6) / 3 = 12.0. Tracking bothtotalandcountsolves this cleanly: updatetotal += valueandcount += 1, then dividetotal / countonce during finalization. - For
minimum, neithertotalnorcountreveals the smallest number seen, so trackminimumand update it whenevervalue < minimum. Always seedminimumwith the cell's first value, never0—otherwise a cell receiving[12, 18]would wrongly report0.
Keeping all three fields (
total,count,minimum) in one compact dictionary per cell usesO(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"]- For
Build the pivot table in two clean passes
With our state helpers in place,
build_pivot_tableseparates cleanly into two passes:- Pass 1 (Accumulate): Validate
aggregationupfront (raisingValueErrorimmediately on unknown names like"avg", even whenrecordsis empty). Stream throughrecordsonce and updatecell_states[row_key][column_key]. - Pass 2 (Finalize): Walk
cell_statesand constructpivot_table[row_key][column_key] = finalize_cell(state, aggregation).
Keeping
cell_statesseparate frompivot_tableensures internal state dictionaries never leak into the output, and in a larger analytics engine the samecell_statescan answer"sum","average", and"minimum"queries without re-scanning raw records.- Pass 1 (Accumulate): Validate
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: 14All three examples match:
{"north": {"web": 30, "retail": 9}, "south": {"web": 14}}for"sum",15.0onnorth/webfor"average", and12onnorth/webfor"minimum".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 theNrecords once, performing twoO(1)expected dictionary lookups and threeO(1)arithmetic updates. Pass 2 visits each of theCpopulated cells once to finalize its metric, and sinceC <= N, overall runtime isO(N)expected. - Space:
O(C). Bothcell_statesand the returnedpivot_tablehold 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. Readingpivot_table[row_key][column_key]performs two hash-table lookups.
Edge cases
- Empty
recordslist: Returns{}for"sum","average", and"minimum", while still raisingValueErrorifaggregationis invalid. - Single record in a cell:
totalandminimumequal that value, andaveragedivides bycount = 1to return that value as a float. - All positive values for
"minimum": Seeding"minimum"fromfirst_valuerather than0ensures[12, 18]returns12(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
minimumto0: Any cell with strictly positive numbers (such as[12, 18]) stays stuck at0; always seed from the cell's first value orfloat("inf"). - Using floor division
//instead of true division/:3 // 2truncates to1, whereas the mean of[1, 2]must be1.5. - Updating a running average without
count: Computingavg = (avg + new_value) / 2over-weights newer records (((12 + 18)/2 + 30)/2 = 22.5instead of20.0). - Returning
collections.defaultdictdirectly: Reading a missing key on adefaultdictsilently inserts an empty dictionary instead of raisingKeyError, mutating the table during read-only lookups. - Silently falling back on unknown
aggregationnames: Without upfront validation, a typo such as"avg"hits a trailingelsebranch 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 inO(N)time, but consumesO(N)memory rather thanO(C). Only needed for order-statistic metrics like exact median that cannot be compressed intoO(1)numbers per cell. - Single-level dictionary keyed by
(row_key, column_key)tuples:table[(row_key, column_key)]also givesO(1)expected cell lookup, but enumerating all columns inside onerow_keythen requires scanning every key in the dictionary instead of readingtable[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?
countis already present in our cell state, andmaximumadds a single float initialized tofirst_valueand updated whenevervalue > state["maximum"]. Population and sample variance also fit inO(1)space per cell by maintaining a running sum of squares alongsidetotalandcount(or Welford's online update to avoid catastrophic floating-point cancellation). Exactmedian, by contrast, cannot be computed inO(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 usingO(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 callfinalize_cellonce 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)andmin(min(a, b), c) == min(a, min(b, c))). Becausetotal,count, andminimumall merge associatively and commutatively, each worker node can independently stream its shard into a localcell_statesmap of sizeO(C), send only those compact per-cell state dictionaries over the network, and let a reducer merge matching(row_key, column_key)states before runningfinalize_cellonce at the end.
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?
- How would you extend your cell states to compute accurate row summaries, column summaries, and a grand total across every aggregation mode?
- If input records are partitioned across many worker nodes, how can you parallelize building the pivot table without skewing averages or minimums?
Similar questions
- Boolean AST Evaluation with Short-Circuiting
- Multi-Column Pivot Table Aggregator
- Pivot Table Class with Cumulative and Summary Totals
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses