Build a Pivot Table with Totals
Updated
Problem statement
You are given shirt-sales records. Each record contains [store, date, color, size, shirtsSold], with shirtsSold represented as a nonnegative decimal string.
Build a pivot table using rowField and columnField, each one of store, date, color, or size. Sort row and column labels lexicographically, sum shirts sold into cells, and maintain row, column, and grand totals.
Return a string matrix with these rows:
- First row: an empty corner cell, the column labels, and
Total. - Each data row: its row label, the cell values, and its row total.
- Last row:
Total, the column totals, and the grand total.
Function
buildPivotTable(records: String[][], rowField: String, columnField: String) → String[][]Examples
Example 1
records = [["A","2026-01-01","red","M","3"],["A","2026-01-02","blue","S","2"],["B","2026-01-01","red","L","4"]]rowField = "store"columnField = "color"return = [["","blue","red","Total"],["A","2","3","5"],["B","0","4","4"],["Total","2","7","9"]]Rows are stores, columns are colors, and the last row and column contain the maintained totals.
Constraints
1 <= records.length <= 100000- Every record has exactly five fields and
shirtsSoldis between0and1000000000. - The grand total fits signed 64-bit arithmetic.
rowField != columnField.- If
RandCare the numbers of distinct selected row and column labels, then(R + 2) * (C + 2) <= 10000, including header and totals cells.
Similar questions at other companies
- Prioritize Products Within Delivery ZonesAmazon · ONSITE INTERVIEW
- Parcel Attribute Store with TTLAirbnb · OAAirbnb interview questions
- Mutual-Friend RecommendationsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Filter, Sort, and Deduplicate Scheduled TasksRippling · PHONE SCREEN · ONSITE INTERVIEWRippling interview questions
- In-Memory Filesystem CommandsPerplexity AI · PHONE SCREEN · ONSITE INTERVIEWPerplexity AI interview questions
- Insert Delete GetRandom O(1)Charta Health · PHONE SCREENCharta Health interview questions
- Longest Consecutive SequenceJP Morgan Chase · PHONE SCREENJP Morgan Chase interview questions
- Top K Frequent Elements with a Recency TiebreakSwiggy · PHONE SCREEN
- Pins Violation Log QueriesPinterest · PHONE SCREENPinterest interview questions
- Group AnagramsWorkday · PHONE SCREEN