Tally Orders per Customer by Status Column
Arrays & HashingAuto-graded · 13 test casesLast updated
Group order records by customer and count how many fall into each requested status, producing one sorted, zero-filled row per customer.
You are given a list of order records and a list of status names. Each order record is a dictionary that contains at least the keys "shopper_id" and "status", and may also contain other keys such as "order_id" or "order_date". Those other keys play no role in this task, so you never need to parse dates.
Build a summary table with one row per shopper. Each row reports how many of that shopper's orders have each of the requested statuses.
Output format
Return a list of dictionaries. Each dictionary has this shape:
{"shopper_id": <id>, <status_1>: <count>, <status_2>: <count>, ...}
Rules
- Every shopper who appears at least once in
ordersgets exactly one row, even if none of their orders has a requested status. In that case all of their counts are0. - Every status in
statusesappears as a key in every row. A status with no matching orders for that shopper has the value0. - Orders whose status is not in
statusesare not counted and do not create new columns. - Status matching is exact and case-sensitive (
"delivered"is not"DELIVERED"). - Rows are sorted by
shopper_idin ascending order using plain string comparison (so"10"comes before"9"). - Within each row, the key order is
"shopper_id"first, followed by the statuses in the order they appear instatuses. - If
statusescontains duplicates, the repeated name yields only a single column. - If
ordersis empty, return an empty list. Ifstatusesis empty, each row contains only"shopper_id".
Constraints
0 <= len(orders) <= 10^50 <= len(statuses) <= 100- Every order has string values for
"shopper_id"and"status". - Status names and shopper ids are case-sensitive strings.
Examples
Example 1
Input: tally_orders_by_status([{'order_id': 'o1', 'shopper_id': 's2', 'order_date': '2024-01-01', 'status': 'DELIVERED'}, {'order_id': 'o2', 'shopper_id': 's1', 'order_date': '2024-01-02', 'status': 'CANCELED'}, {'order_id': 'o3', 'shopper_id': 's2', 'order_date': '2024-01-03', 'status': 'DELIVERED'}, {'order_id': 'o4', 'shopper_id': 's2', 'order_date': '2024-01-04', 'status': 'RETURNED'}], ['DELIVERED', 'CANCELED', 'RETURNED'])
Output: [{'shopper_id': 's1', 'DELIVERED': 0, 'CANCELED': 1, 'RETURNED': 0}, {'shopper_id': 's2', 'DELIVERED': 2, 'CANCELED': 0, 'RETURNED': 1}]
Hints
Hint 1
Think of this as a GROUP BY with conditional counting: one pass over the orders, keeping a counter table per shopper.
Hint 2
The first time you see a shopper, create their counter table with every requested status set to 0. That guarantees all columns exist and that shoppers with only unrequested statuses still appear.
Hint 3
Only increment a counter if the order's status is a key in that shopper's table; sort the shopper ids once at the end and build each output row with shopper_id first.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is an in-memory version of a SQL GROUP BY with conditional counts (SUM(CASE WHEN status = ... THEN 1 ELSE 0 END)).
Keep a dictionary that maps each shopper id to an inner dictionary of status -> count. Walk through the orders once:
- When a shopper is seen for the first time, create their inner dictionary with every requested status set to
0. This makes sure all columns exist and that a shopper whose orders all have unrequested statuses still gets an all-zero row. - For each order, increment the counter only if the order's status is a key of that shopper's inner dictionary. Because the inner keys are exactly the requested statuses, this membership test is also the filter that ignores everything else.
- After the pass, sort the shopper ids as strings and build one flat dictionary per shopper, placing
shopper_idfirst and then the statuses in their input order (Python dictionaries preserve insertion order).
The order_date field is never read, so no date parsing is needed.
Why it is correct
- Every shopper gets a row because an entry is created the first time any of their orders is seen, before the status check.
- Each order is visited once and adds at most 1 to a single cell: its own shopper's counter for its own status. So each cell equals the number of that shopper's orders with that status.
- The inner dictionary keys are exactly the set of requested statuses, so unrequested statuses are never counted and never become columns. Duplicate status names collapse into one key.
- Sorting the keys of the outer dictionary gives the required string-order of rows, and building rows by unpacking in insertion order gives the required key order.
Complexity
Let n be the number of orders, s the number of distinct shoppers and k the number of statuses.
- Time: O(n + s*k + s log s). Each order costs O(1) hashing, each new shopper costs O(k) to initialize, and sorting costs O(s log s).
- Space: O(s*k) for the counting table, which equals the size of the output.
Reference solution
from typing import Dict, List
def tally_orders_by_status(orders: List[Dict[str, str]], statuses: List[str]) -> List[Dict[str, int]]:
counts: Dict[str, Dict[str, int]] = {}
for order in orders:
shopper_id = order["shopper_id"]
if shopper_id not in counts:
counts[shopper_id] = {status: 0 for status in statuses}
status = order["status"]
if status in counts[shopper_id]:
counts[shopper_id][status] += 1
return [
{"shopper_id": shopper_id, **counts[shopper_id]}
for shopper_id in sorted(counts)
]