Group orders by customer and find the top 3 products with Counter

Backend Live Coding November 13, 2026 python

The interviewer wants to see that you know the standard library: collections (Counter, defaultdict, deque), itertools (groupby, chain, islice), heapq (nlargest).

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# ======================================================================
# Q: Group orders by customer and find the 3 best-selling products (without a
# database).
#
# The interviewer wants to see that you know the standard library: collections
# (Counter, defaultdict, deque), itertools (groupby, chain, islice), heapq
# (nlargest).
# ======================================================================

from collections import Counter, defaultdict

by_customer = defaultdict(list)
for o in orders:
    by_customer[o['customer_id']].append(o)

sold = Counter()
for o in orders:
    for item in o['items']:
        sold[item['sku']] += item['qty']
top3 = sold.most_common(3)