Join User Profiles and Purchase Records, Fill Gaps, Compute Line Spend
SQL & DataAuto-graded · 14 test casesLast updated
Tests left-join logic, mode imputation for missing categorical fields, and null-safe row-level spend calculation using plain Python dicts.
Join User Profiles and Purchase Records, Fill Gaps, Compute Line Spend
You receive two lists of dictionaries representing a members table and a purchases table.
members — one entry per member:
| Field | Type | Notes |
|---|---|---|
id | int | unique member identifier |
name | str | display name |
country | str or None | home country; may be missing |
purchases — one entry per purchase:
| Field | Type | Notes |
|---|---|---|
id | int | unique purchase identifier |
customer_id | int | foreign key into members |
amount | float or None | purchase value; may be missing |
Task
Return a flat list of dictionaries, one row per purchase, keeping every member even if they made no purchases. Each output row must contain exactly these keys:
| Key | Value |
|---|---|
id | the member's id |
name | the member's name |
country | the member's country after imputation (see below) |
order_id | the purchase's id, or None if the member has no purchases |
amount | the raw purchase amount (unchanged, so possibly None), or None if no purchases |
total_spent | 0 if amount is None or the member has no purchases; otherwise equal to amount |
Filling missing countries
Before building output rows, determine an imputed country to substitute for any None country value:
- Collect all non-
Nonecountry values from the members list only (not from the joined result). - Find the mode — the country appearing most often.
- Break ties by choosing the country that comes first alphabetically.
- If every member's country is
None, do not replace any values; leave them asNone.
Apply the imputed country to every member whose country is None.
Sorting
Return the final list sorted by total_spent descending. The relative order among rows with equal total_spent is not specified.
Constraints
1 ≤ len(members) ≤ 10 0000 ≤ len(purchases) ≤ 50 000- Every
purchase.customer_idappears inmembers. amount, when present, is a non-negative float.- A member may have zero, one, or many purchases.
idvalues within each table are unique.
Examples
Example 1
Input: merge_and_clean_customer_orders([{'id': 1, 'name': 'Alice', 'country': 'US'}, {'id': 2, 'name': 'Bob', 'country': 'UK'}, {'id': 3, 'name': 'Charlie', 'country': None}], [{'id': 101, 'customer_id': 1, 'amount': 250.5}, {'id': 102, 'customer_id': 2, 'amount': 99.99}, {'id': 103, 'customer_id': 2, 'amount': None}])
Output: [{'id': 1, 'name': 'Alice', 'country': 'US', 'order_id': 101, 'amount': 250.5, 'total_spent': 250.5}, {'id': 2, 'name': 'Bob', 'country': 'UK', 'order_id': 102, 'amount': 99.99, 'total_spent': 99.99}, {'id': 2, 'name': 'Bob', 'country': 'UK', 'order_id': 103, 'amount': None, 'total_spent': 0}, {'id': 3, 'name': 'Charlie', 'country': 'UK', 'order_id': None, 'amount': None, 'total_spent': 0}]
Hints
Hint 1
Index purchases by customer_id into a dict before the main loop so each member's purchases are found in O(1) instead of scanning the full list each time.
Hint 2
To find the mode with an alphabetical tie-break, count frequencies with a plain dict, then select the winner with min(counts, key=lambda c: (-counts[c], c)) — negative frequency puts the most-common country first, and the string itself resolves ties alphabetically.
Hint 3
A member with no purchases should still appear exactly once in the output, with order_id=None and amount=None. Don't confuse amount (left raw as None) with total_spent (always a number, defaulting to 0).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has four clean stages: impute the missing country, index the orders, perform the left join, then sort.
Stage 1 — Impute the missing country
Scan customers once and collect every non-None country into a frequency dictionary. To find the mode with a deterministic tie-break, call:
min(counts, key=lambda c: (-counts[c], c))
The negative frequency means higher counts compare as smaller, so the most-frequent country wins. When two countries share the top frequency, the plain string comparison selects the alphabetically earlier one. This runs in O(U) where U = number of members.
Do this before the join. If you waited until after, a member with many orders would appear multiple times and inflate their country's frequency.
Stage 2 — Index orders by customer
Build a dict mapping each customer_id to a list of its orders. This is O(T) up front but makes every per-member lookup in stage 3 O(1).
Stage 3 — Left join with a sentinel
Iterate over every member. Apply the imputed country if needed. Retrieve that member's order list; if it is empty, substitute [None] so the inner loop runs exactly once and emits the required placeholder row.
For each order (or sentinel):
amountin the output is the raw value — preserved asNonewhen missing, never normalised.total_spentis0when the order is the sentinel or whenamountisNone; otherwise it equalsamount.
Stage 4 — Sort
list.sort with key=lambda row: -row["total_spent"] sorts descending in O(N log N). Python's sort is stable, so equal-total_spent rows retain their original insertion order.
Why this is correct
- Every member appears at least once because the sentinel prevents the inner loop from being skipped.
- The mode is computed over distinct member records, so no member is counted more than once regardless of how many orders they have.
amountis never modified; onlytotal_spentsubstitutes 0 for missing values, matching the expected output format exactly.
Complexity
Let U = members, T = orders, N ≤ U + T (output rows).
- Time: O(U) mode computation + O(T) indexing + O(N) join loop + O(N log N) sort → O(N log N) overall.
- Space: O(U + T) for the index and output list → O(N).
Edge cases
- All countries missing — the frequency dict is empty;
mode_countrystaysNoneand no substitution is made. - Tied mode — alphabetical first wins deterministically via the
minkey. - Member with no orders — exactly one output row;
order_idandamountare bothNone,total_spentis0. - Order with
amount=None—amountstaysNonein the output;total_spentbecomes0.
Reference solution
from typing import Dict, List
def merge_and_clean_customer_orders(customers: List[Dict], orders: List[Dict]) -> List[Dict]:
# 1. Compute mode country from members only; alphabetical tie-break.
countries = [c.get("country") for c in customers if c.get("country") is not None]
if countries:
counts: Dict[str, int] = {}
for country in countries:
counts[country] = counts.get(country, 0) + 1
mode_country = min(counts, key=lambda c: (-counts[c], c))
else:
mode_country = None
# 2. Index orders by customer_id for O(1) lookup.
orders_by_customer: Dict[int, list] = {}
for order in orders:
orders_by_customer.setdefault(order.get("customer_id"), []).append(order)
# 3. Left join: every member produces at least one output row.
result = []
for customer in customers:
country = customer.get("country")
if country is None:
country = mode_country
customer_orders = orders_by_customer.get(customer.get("id"), [])
if not customer_orders:
customer_orders = [None] # sentinel ensures one placeholder row
for order in customer_orders:
if order is None or order.get("amount") is None:
total_spent = 0
else:
total_spent = order["amount"]
result.append({
"id": customer.get("id"),
"name": customer.get("name"),
"country": country,
"order_id": None if order is None else order.get("id"),
"amount": None if order is None else order.get("amount"),
"total_spent": total_spent,
})
# 4. Sort by total_spent descending.
result.sort(key=lambda row: -row["total_spent"])
return result