KatInterview

Cross-Tabulate Records by Composite Row and Column Keys

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashinghash-mapgroupingaggregation

Last updated

Group records by composite row and column keys, sum a value field per pair, and return the axes in first-seen order with a dense grid that has zeros for missing pairs.

You are given a list of records, where each record is a dictionary mapping column names to values. Build a cross-tabulation (a pivot table) that sums one numeric column over groups defined by two sets of key columns.

Task

Implement a function that takes:

  • rows: a list of dictionaries, each mapping a column name (string) to a value (string or number).
  • row_key_columns: a list of column names. Together, their values in a record form that record's row key.
  • col_key_columns: a list of column names. Together, their values in a record form that record's column key.
  • value_column: the name of the numeric column to add up.

Return a dictionary with exactly three entries:

  • "row_keys": the distinct row keys, each written as a list of values in the same order as row_key_columns.
  • "col_keys": the distinct column keys, each written as a list of values in the same order as col_key_columns.
  • "values": a 2D list with one inner list per row key and one entry per column key. Entry values[i][j] is the sum of value_column over all records whose row key is row_keys[i] and whose column key is col_keys[j].

Rules

  • Ordering: Row keys and column keys appear in the order in which they are first encountered while scanning rows from start to finish. Do not sort them.
  • Missing pairs: If no record has a particular (row key, column key) pair, the corresponding cell is 0.
  • Distinctness: Two keys are the same only if all their components are equal. Keys with different components in different positions are different keys.
  • Empty input: If rows is empty, return {"row_keys": [], "col_keys": [], "values": []}.
  • Every record contains all the columns that are referenced.
  • Key values are kept as they appear in the input (for example, the integer 2023 stays an integer).

Constraints

  • 0 <= len(rows) <= 50,000
  • row_key_columns and col_key_columns each contain at least one column name, and the value column is not listed in either.
  • Value-column entries are integers or floats.
  • The number of distinct row keys times distinct column keys is small enough to hold the dense grid in memory.
  • Aim for roughly linear time in the number of records, plus the size of the output grid.

Examples

Example 1

Input: build_cross_tab([{'city': 'SF', 'product': 'Book', 'sales': 10}, {'city': 'SF', 'product': 'Pen', 'sales': 4}, {'city': 'NY', 'product': 'Book', 'sales': 7}, {'city': 'SF', 'product': 'Book', 'sales': 3}], ['city'], ['product'], 'sales')

Output: {'row_keys': [['SF'], ['NY']], 'col_keys': [['Book'], ['Pen']], 'values': [[13, 4], [7, 0]]}

Example 2

Input: build_cross_tab([{'region': 'West', 'quarter': 1, 'product': 'A', 'amount': 5}, {'region': 'West', 'quarter': 1, 'product': 'B', 'amount': 8}, {'region': 'West', 'quarter': 2, 'product': 'A', 'amount': 6}, {'region': 'East', 'quarter': 1, 'product': 'A', 'amount': 4}], ['region', 'quarter'], ['product'], 'amount')

Output: {'row_keys': [['West', 1], ['West', 2], ['East', 1]], 'col_keys': [['A'], ['B']], 'values': [[5, 8], [6, 0], [4, 0]]}

Example 3

Input: build_cross_tab([{'department': 'Eng', 'year': 2023, 'team': 'A', 'hours': 10}, {'department': 'Eng', 'year': 2023, 'team': 'A', 'hours': 2}, {'department': 'Sales', 'year': 2024, 'team': 'B', 'hours': 7}], ['department'], ['year', 'team'], 'hours')

Output: {'row_keys': [['Eng'], ['Sales']], 'col_keys': [[2023, 'A'], [2024, 'B']], 'values': [[12, 0], [0, 7]]}

Hints

Hint 1

Turn each record's key columns into a tuple. Tuples are hashable, so they can be used as dictionary keys, and a list of columns of any length is handled uniformly.

Hint 2

Record each distinct row key and column key the first time you see it, together with its position index. A dictionary from key to index gives you first-seen ordering and constant-time lookup.

Hint 3

Once you know how many distinct row keys and column keys there are, create a grid of zeros of that size, then add each record's value to the cell at its (row index, column index).