Nearest Profiles by Masked Mean Squared Error
Heaps, Sorting & SearchAuto-graded · 14 test casesLast updated
Tests pairwise distance computation with a missing-data-aware MSE metric, tie-breaking, and top-K ranking across user profiles.
Problem
You have a collection of user profiles. Each profile has a unique string identifier ("user_id") and some number of numeric feature fields. Feature values may be absent (represented as None or simply missing from the dict).
Your task is to find the 5 closest profiles to each user, where closeness is measured by a missing-data-aware Mean Squared Error (MSE).
Distance Definition
For two profiles P and Q, let the shared features be every feature key where both profiles have a non-None value.
- If the number of shared features is less than 2, the pair is considered incomparable and must be excluded from all neighbor lists.
- Otherwise, the distance is:
distance(P, Q) = sum((P[f] - Q[f])^2 for f in shared features) / |shared features|
The divisor is the count of shared features, not the total number of features in the dataset.
What to Return
Return a dictionary mapping every user_id to a list of up to 5 other user_ids, ordered by:
- Distance ascending
user_idlexicographically ascending as a tie-breaker
A profile is never its own neighbor. If a profile has no comparable neighbors, map it to an empty list. Lists may contain fewer than 5 entries when fewer comparable profiles exist.
Input Format
A list of dicts. Each dict contains:
"user_id": a non-empty string, unique across all profiles- Zero or more feature keys mapped to
float/intvalues, orNone
Feature keys are derived from the keys present in the input (excluding "user_id"). A key absent from a dict is treated the same as None.
Constraints
- 0 ≤ number of profiles ≤ 1,000
- 0 ≤ number of feature columns ≤ 50
user_idvalues are non-empty strings- Numeric feature values, when present, are finite floats or ints
NaNwill not appear; absent orNonevalues represent missingness- An empty input list must return an empty dict
Examples
Example 1
Input: find_closest_profiles([{'user_id': 'A', 'f1': 1, 'f2': 2}, {'user_id': 'B', 'f1': 1.2, 'f2': 2.1}, {'user_id': 'C', 'f1': 5, 'f2': 5}])
Output: {'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['B', 'A']}
Hints
Hint 1
For each ordered pair (i, j), iterate over the feature keys and accumulate squared differences only where both profiles have a non-None value. Track the count of those shared features separately from the total.
Hint 2
Before computing any distances, collect the full list of feature keys once (everything except 'user_id' in the first row). Use dict.get(key) so that missing keys are treated as None automatically.
Hint 3
After collecting each user's candidate list of (distance, neighbor_id) tuples, sort by (distance, neighbor_id) to get ascending distance with lexicographic tie-breaking, then slice [:5].
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core task is all-pairs pairwise distance with a twist: missing values are skipped rather than imputed, and pairs that don't share at least two features are treated as infinitely far apart.
Step-by-step
-
Extract feature keys once. Read every key from the first row except
"user_id". This list is reused for every pair, so the work is O(m) up front. -
Nested loop over pairs. For each profile
i, iterate over every other profilej. For each feature key, call.get(key)on both dicts — this handles absent keys and explicitNonevalues uniformly. -
Accumulate only shared observations. When both values are non-
None, add(a - b)²to a running sum and increment a counter. This keeps the metric honest: it's a true mean over the observed overlap, so a pair sharing 2 features is directly comparable to one sharing 50. -
Apply the minimum-features guard. If
common < 2after the inner loop, the pair is incomparable and is simply not added to the candidate list. It will never appear as a neighbor. -
Sort candidates. Each user's list of
(distance, neighbor_id)tuples is sorted by(distance, neighbor_id)— ascending distance first, lexicographic user_id as a tie-breaker. This exactly satisfies the two-level ordering requirement. -
Slice to top 5.
candidates[:5]naturally returns fewer entries when fewer comparable profiles exist.
Why it's correct
- The divisor is
common(the overlap size), not the total feature countm, so missing data doesn't shrink distances artificially. - Using
i == jfor self-exclusion works regardless of whetheruser_idvalues are duplicated elsewhere. - Sorting on the tuple
(distance, user_id)is deterministic and matches the required tie-breaking rule. - Edge cases fall out naturally: an all-null profile has
common = 0with everyone, so its list is empty; it also never appears in any other profile's list.
Complexity
| Step | Cost |
|---|---|
| Distance computation | O(n² · m) — at the limits, ~10⁶ pairs × 50 features = 5×10⁷ ops |
| Sorting | O(n · n log n) total across all users |
| Space | O(n) candidates per user; O(5n) for the output |
The O(n² · m) distance step dominates. At n = 1,000 and m = 50 this is comfortably fast in pure Python. For larger n, the inner loop can be replaced with a NumPy masked-matrix computation, or approximate nearest-neighbor methods (FAISS, HNSW) can be used with exact re-ranking of a shortlist.
Reference solution
from typing import Dict, List
def find_closest_profiles(rows: List[Dict]) -> Dict[str, List[str]]:
if not rows:
return {}
# Collect feature keys once from the first row, excluding the id field.
feature_keys = [key for key in rows[0] if key != "user_id"]
result: Dict[str, List[str]] = {}
for i, profile in enumerate(rows):
candidates = []
for j, other in enumerate(rows):
if i == j:
continue # a profile is never its own neighbor
squared_error = 0.0
common = 0
for key in feature_keys:
a = profile.get(key)
b = other.get(key)
if a is not None and b is not None:
diff = a - b
squared_error += diff * diff
common += 1
# Fewer than 2 shared features => incomparable => skip entirely.
if common >= 2:
candidates.append((squared_error / common, other["user_id"]))
# Primary sort: distance ascending. Secondary sort: user_id lexicographic.
candidates.sort(key=lambda item: (item[0], item[1]))
result[profile["user_id"]] = [uid for _, uid in candidates[:5]]
return result