The Response Aggregator
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L3
- Asked in
- Viking
Problem
Given pages (a list of pages, each a list of dicts with 'category' and 'amount'), sum amounts per category across all pages. Return a list of [category, total] pairs sorted by total descending, tie-break alphabetically by category.
Multiple result pages. One clean summary.
Example
Input:
pages = [[{"amount":50,"category":"food"},{"amount":200,"category":"travel"}],[{"amount":30,"category":"food"},{"amount":75,"category":"office"}]]Output:
[["travel",200],["food",80],["office",75]]
Worked solution and explanation
Why this problem exists in real interviews
This tests flattening paginated data and aggregating by category, a common ETL pattern when consuming paginated API responses. It checks whether candidates can handle two levels of iteration and produce a correctly sorted list of results.
Break down the requirements
Step 1: Flatten all pages into a single stream of records
Iterate through each page, then each record within the page.
Step 2: Accumulate totals by category
Use a dictionary to sum amounts per category across all pages.
Step 3: Sort and return a list of pairs
Convert the dict to a list of [category, total] pairs, then sort by total descending with an alphabetical tie-break on category.
The solution
def aggregate_pages(pages):
totals = {}
for page in pages:
for record in page:
cat = record['category']
amt = record['amount']
if cat in totals:
totals[cat] += amt
else:
totals[cat] = amt
pairs = [[cat, total] for cat, total in totals.items()]
pairs.sort(key=lambda p: (-p[1], p[0]))
return pairsCommon follow-up questions
- What if pages were fetched lazily from an API? (Tests async iteration or generator-based page fetching.)
- What if some records had missing 'amount' fields? (Tests using `.get('amount', 0)` for defensive access.)
- How would you handle this with pandas? (Tests pd.concat + groupby + `sort_values`.)