Build Pivot Table Subtotals And Grand Totals From Rows

Last updated: November 29, 2026

Quick Overview

Given flat rows and an ordered list of grouping columns, return display rows for a grouped table: a detail row for each deepest group, a subtotal row after each group at every shallower level, and a grand total at the end, all in one pass after sorting.

Sigma Computing
Coding & Algorithms
Software Engineer
Sigma Computing
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Given flat rows and an ordered list of grouping columns, return display rows for a grouped table: a detail row for each deepest group, a subtotal row after each group at every shallower level, and a grand total at the end, all in one pass after sorting.

Sigma tables can be grouped by several levels with subtotals, similar to a pivot. Even though the real product pushes this into SQL with GROUPING SETS or ROLLUP, the screen checks whether you can produce the hierarchy correctly in code and reason about how it maps to SQL.

What the Interviewer Expects
  • Sort by the grouping key tuple so groups are contiguous
  • Detect the shallowest level where the key changed and close every deeper group
  • Emit subtotals in the right order: deepest first, then parents
  • Keep running totals per depth rather than recomputing
  • Explain the SQL equivalent (GROUP BY ROLLUP) and when to compute in the warehouse instead
Key Topics to Cover
grouping
rollup
sorting
streaming aggregation
GROUPING SETS
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you support averages, where subtotals cannot be summed from children?
  • How would you produce the same output with one SQL query, and how do you tell subtotal rows from real NULL group values?
  • How would you page through this output when there are 2 million detail groups?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input rows are dicts; levels is like ['region', 'product']; measure is summed. Output rows carry the group labels (None for rolled-up levels), the sum, a kind and a depth....

High-Level Design

After sorting, walk rows and maintain totals[d], the running sum for the open group at depth d (depth 0 is the grand total). When the key changes, find the first level that differs. Every open gro...


Submit Your Answer
Markdown supported

Related Questions