Deduplicate and Reconcile Customer Records
SQL & DataAuto-graded · 13 test casesLast updated
Tests the ability to clean a list of messy customer records by deduplicating on a canonical key, resolving field conflicts with explicit priority rules, and returning a sorted, normalized result.
Deduplicate and Reconcile Customer Records
You are given a list of customer records extracted from multiple data sources. Because records were inserted by different systems over time, the same customer may appear more than once with conflicting or missing field values.
Each record is a dictionary with the following keys:
| Key | Type | Notes |
|---|---|---|
"id" | str | A non-empty alphanumeric customer ID. Case-insensitive — "C001" and "c001" are the same customer. |
"name" | str or None | Customer's full name. May be None or an empty string "". |
"email" | str or None | Customer's email. May be None or an empty string "". |
"score" | int or None | An engagement score. May be None. |
Your task is to implement reconcile_customers(records) which returns a cleaned, deduplicated list of customer records.
Deduplication Key
Two records refer to the same customer if and only if their "id" fields are equal after lower-casing.
Field Reconciliation Rules (applied per customer group)
After grouping all records for the same customer, produce a single merged record using these rules in order:
"id"— Use the lower-cased version of the ID."name"— Use the first non-empty, non-Nonevalue encountered, where "first" means the record appears earliest in the input list. If all values are empty/None, useNone."email"— Same rule asname: first non-empty, non-Nonevalue by input order. If all are empty/None, useNone."score"— Use the maximum non-Nonevalue across all records for that customer. If all values areNone, useNone.
Output Requirements
- Return a list of merged records (one per unique customer ID).
- Sort the output list ascending by the normalized (lower-cased)
"id"field. - Every returned record must contain exactly the four keys:
"id","name","email","score".
Constraints
0 ≤ len(records) ≤ 2000- Each record is guaranteed to contain all four keys (
"id","name","email","score"). "id"is always a non-empty string containing only ASCII letters and digits."name"and"email"are eitherNone,"", or a non-empty string."score"is eitherNoneor a non-negative integer.- Input order is the order records appear in the input list (index 0 first).
Examples
Example 1
Input: reconcile_customers([{'id': 'C001', 'name': 'Alice', 'email': '[email protected]', 'score': 80}, {'id': 'c001', 'name': None, 'email': '', 'score': 95}, {'id': 'C002', 'name': 'Bob', 'email': None, 'score': None}])
Output: [{'id': 'c001', 'name': 'Alice', 'email': '[email protected]', 'score': 95}, {'id': 'c002', 'name': 'Bob', 'email': None, 'score': None}]
Example 2
Input: reconcile_customers([])
Output: []
Example 3
Input: reconcile_customers([{'id': 'X10', 'name': None, 'email': None, 'score': None}, {'id': 'X10', 'name': '', 'email': '[email protected]', 'score': 10}, {'id': 'X10', 'name': 'Xander', 'email': '[email protected]', 'score': 5}])
Output: [{'id': 'x10', 'name': 'Xander', 'email': '[email protected]', 'score': 10}]
Hints
Hint 1
Group records by lowercased ID while preserving original input order — an ordered dict or a list-of-indices approach works well.
Hint 2
For name and email, a simple loop that returns the first truthy string value handles both None and empty-string cases in one pass.
Hint 3
For score, use the built-in max() with a default of None, filtering out None values first; if the filtered list is empty, the result is None.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem breaks into three clean steps: group, merge, sort.
Step 1 — Group by normalized ID
Iterate through the input records in order. For each record, compute key = record["id"].lower() and append the record to a list stored at groups[key]. Using a plain dict (which preserves insertion order in Python 3.7+) is enough to keep per-group ordering aligned with input order.
Step 2 — Merge each group
For each group of records sharing a normalized ID:
id: already the dict key — use it directly.name/email: Walk the group in order; return the first value that is notNoneand not"". If no such value exists, the result isNone. This single pass handles both falsy cases uniformly.score: Collect all non-Nonescores into a list.max()of that list gives the answer; if the list is empty, result isNone.
Step 3 — Sort
Sort the merged list by the "id" field (already lower-cased), ascending. Python's default string sort on ASCII-alphanumeric IDs is lexicographic, which is the correct and unambiguous ordering here.
Why this is correct
- Grouping by
lower()satisfies the case-insensitive deduplication requirement. - Walking the list in original input index order for
name/emailrespects the "earliest in input" tie-break. - Taking
maxforscoreis a simple one-liner with thedefault=Nonefallback via an empty-list check.
Complexity
- Time: O(N log N) dominated by the final sort; grouping and merging are O(N) overall.
- Space: O(N) for the groups dictionary and the output list.
from typing import List, Dict, Any
def reconcile_customers(records: list) -> list:
# Preserve insertion order per group
groups: dict = {} # normalized_id -> list of records in input order
for rec in records:
key = rec["id"].lower()
if key not in groups:
groups[key] = []
groups[key].append(rec)
merged = []
for norm_id, group in groups.items():
# name: first non-empty, non-None
name = None
for rec in group:
if rec["name"] is not None and rec["name"] != "":
name = rec["name"]
break
# email: first non-empty, non-None
email = None
for rec in group:
if rec["email"] is not None and rec["email"] != "":
email = rec["email"]
break
# score: max of non-None values
scores = [rec["score"] for rec in group if rec["score"] is not None]
score = max(scores) if scores else None
merged.append({
"id": norm_id,
"name": name,
"email": email,
"score": score,
})
merged.sort(key=lambda r: r["id"])
return merged