Deduplicate and Canonicalize Customer Records
SQL & DataAuto-graded · 15 test casesLast updated
Tests ability to clean a list of raw customer record dicts by resolving duplicates, normalizing fields, and returning one canonical record per customer.
Deduplicate and Canonicalize Customer Records
You are given a list of raw customer records extracted from a database. Due to multiple data-entry sources, the same customer may appear several times with slightly inconsistent data. Your job is to clean this list and return exactly one canonical record per customer.
Record Structure
Each record is a dict with these keys:
| Key | Type | Notes |
|---|---|---|
customer_id | str | May have leading/trailing whitespace; case-insensitive (e.g. "C001" and " c001 " are the same customer) |
name | str | May have extra whitespace; keep the longest stripped version across duplicates; tie-break: lexicographically largest |
email | str | Lowercase it; keep the most frequent email among duplicates; tie-break: lexicographically smallest |
spend | float or int | Keep the maximum value across duplicates |
active | bool | True wins over False (i.e. if any duplicate is active, the canonical record is active) |
Canonicalization Rules (applied per customer group)
customer_id: Strip whitespace and uppercase (e.g." c001 "→"C001").name: Strip each name variant, then pick the longest. On a length tie, pick the lexicographically largest string.email: Lowercase all variants, then pick the most frequent. On a frequency tie, pick the lexicographically smallest.spend: Maximum across all duplicates.active:Trueif any duplicate hasTrue, otherwiseFalse.
Output
Return a list of canonical records (one per unique customer_id), sorted ascending by canonical customer_id.
Each returned dict must have exactly the keys: customer_id, name, email, spend, active.
Constraints
0 ≤ len(records) ≤ 2000- Every record contains all five keys.
customer_idafter stripping is always a non-empty string.spendvalues are finite numbers in the range[0, 1_000_000].- There is always at least one record per customer group (no empty groups).
- The input list may already be fully deduplicated, or every record may be a duplicate.
Examples
Example 1
Input: deduplicate_customers([{'customer_id': ' c001 ', 'name': 'Alice Smith', 'email': '[email protected]', 'spend': 120, 'active': True}, {'customer_id': 'C001', 'name': 'Alice M Smith', 'email': '[email protected]', 'spend': 95.5, 'active': False}, {'customer_id': 'c001', 'name': 'Alice Smith', 'email': '[email protected]', 'spend': 200, 'active': False}])
Output: [{'customer_id': 'C001', 'name': 'Alice M Smith', 'email': '[email protected]', 'spend': 200, 'active': True}]
Example 2
Input: deduplicate_customers([{'customer_id': 'B002', 'name': 'Bob', 'email': '[email protected]', 'spend': 50, 'active': False}, {'customer_id': 'A001', 'name': 'Ana Ruiz', 'email': '[email protected]', 'spend': 300, 'active': True}])
Output: [{'customer_id': 'A001', 'name': 'Ana Ruiz', 'email': '[email protected]', 'spend': 300, 'active': True}, {'customer_id': 'B002', 'name': 'Bob', 'email': '[email protected]', 'spend': 50, 'active': False}]
Example 3
Input: deduplicate_customers([])
Output: []
Hints
Hint 1
Start by normalizing each customer_id (strip + uppercase) so you can group records that belong to the same customer.
Hint 2
For the email field, use a frequency counter (collections.Counter) per group, then resolve ties with min() on the candidates that share the top count.
Hint 3
Build each canonical record field-by-field from the group, then collect all canonical records into a list and sort by customer_id before returning.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem breaks down into three clean phases:
Phase 1 – Group by normalized customer_id
Iterate over every record. Compute the canonical ID by calling .strip().upper() on the raw customer_id, then bucket the record into a defaultdict(list) keyed by that canonical ID. This handles all whitespace and casing variants in one pass — O(n).
Phase 2 – Resolve each group to a single canonical record
For each bucket (one customer), apply the five field rules independently:
customer_id: Already the dict key; use it directly.name: Strip each name variant. Find the maximum length. Among all names of that maximum length, take the lexicographically largest withmax(...).email: Lowercase all variants. Build aCounter. Find the highest frequency. Among all emails tied at that frequency, take the lexicographically smallest withmin(...).spend:max(r["spend"] for r in recs).active:any(r["active"] for r in recs).
Each of these is O(g) where g is the group size, so the total across all groups is O(n).
Phase 3 – Sort and return
Collect all canonical records and call .sort(key=lambda x: x["customer_id"]). String sorting in Python is lexicographic, which matches the requirement. This is O(k log k) where k is the number of unique customers.
Why it is correct
- Normalization before grouping guarantees that all spelling variants of the same ID land in the same bucket.
- Each tie-break rule is deterministic:
max/minon strings uses Python's standard lexicographic ordering, andCountergives exact frequencies — no ambiguity remains. any()short-circuits but is still correct for the OR-semantics ofactive.
Complexity
| Time | Space | |
|---|---|---|
| Grouping | O(n) | O(n) |
| Canonicalization | O(n) total | O(n) |
| Sorting output | O(k log k) | O(k) |
| Overall | O(n + k log k) | O(n) |
Since k ≤ n, the whole solution is O(n log n) in the worst case.
from collections import defaultdict, Counter
def deduplicate_customers(records: list) -> list:
groups = defaultdict(list)
for rec in records:
canonical_id = rec["customer_id"].strip().upper()
groups[canonical_id].append(rec)
result = []
for cid, recs in groups.items():
# name: strip each, longest, then lex largest on tie
names = [r["name"].strip() for r in recs]
max_len = max(len(n) for n in names)
best_name = max(n for n in names if len(n) == max_len)
# email: lowercase, most frequent, lex smallest on tie
emails = [r["email"].lower() for r in recs]
freq = Counter(emails)
max_freq = max(freq.values())
best_email = min(e for e, c in freq.items() if c == max_freq)
# spend: maximum
best_spend = max(r["spend"] for r in recs)
# active: any True
best_active = any(r["active"] for r in recs)
result.append({
"customer_id": cid,
"name": best_name,
"email": best_email,
"spend": best_spend,
"active": best_active,
})
result.sort(key=lambda x: x["customer_id"])
return result