Rank Nearest Neighbors by Mean Squared Error
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests k-nearest neighbors search with distance computation, NULL handling, and top-k selection with tie-breaking.
You are building a nearest-neighbor matcher that compares query records against a reference dataset.
You are given two lists of records represented as dictionaries. Each record contains an ID field and one or more numeric feature fields.
Input:
-
target_rows: A list of dictionaries, where each dictionary has:target_id(string): unique identifier for the target recordf1, f2, ..., fk(float orNone): numeric feature values that may be missing (None)
-
candidate_rows: A list of dictionaries, where each dictionary has:candidate_id(string): unique identifier for the candidate recordf1, f2, ..., fk(float orNone): numeric feature values that may be missing (None)
Both lists share the same set of feature column names (everything except the ID field).
Task:
For each target record, identify the 5 closest candidate records based on mean squared error (MSE) computed across all features.
Distance Calculation:
For a target-candidate pair, compute MSE using only the features where both records have non-None values:
- Let the shared non-
Nonefeatures be the set wheretarget[feature]is notNoneANDcandidate[feature]is notNone - MSE = (sum of squared differences) / (count of shared features)
- If no features are shared (all are
Nonein at least one record), the distance isNone
Use raw feature values without any normalization or scaling.
Output:
Return a list of dictionaries, where each dictionary contains:
target_id(string): the target record identifiercandidate_id(string): the matched candidate identifierdistance(float orNone): the computed MSE distancerank(int): rank from 1 to 5, where 1 is the closest match
Ordering and Tie-Breaking:
- Numeric distances are ordered from smallest to largest
Nonedistances are treated as infinitely large (sorted after all numeric distances)- When distances are equal, preserve the original order of candidates from the input list (stable sort)
- Return at most 5 candidates per target (fewer if there are fewer than 5 candidates total)
- Results should be grouped by target (in input order), then by rank (ascending)
Constraints:
- 1 ≤ len(target_rows) ≤ 100
- 0 ≤ len(candidate_rows) ≤ 1000
- 1 ≤ number of features ≤ 20
- Feature values, when present, are in the range [-1000, 1000]
- All target IDs are unique; all candidate IDs are unique
Examples
Example 1
Input: rank_nearest_neighbors([{'target_id': 't1', 'f1': 1, 'f2': 2}, {'target_id': 't2', 'f1': 5, 'f2': 5}], [{'candidate_id': 'c1', 'f1': 1, 'f2': 3}, {'candidate_id': 'c2', 'f1': 4, 'f2': 4}, {'candidate_id': 'c3', 'f1': 5, 'f2': 5}])
Output: [{'target_id': 't1', 'candidate_id': 'c1', 'distance': 0.5, 'rank': 1}, {'target_id': 't1', 'candidate_id': 'c2', 'distance': 6.5, 'rank': 2}, {'target_id': 't1', 'candidate_id': 'c3', 'distance': 12.5, 'rank': 3}, {'target_id': 't2', 'candidate_id': 'c3', 'distance': 0, 'rank': 1}, {'target_id': 't2', 'candidate_id': 'c2', 'distance': 1, 'rank': 2}, {'target_id': 't2', 'candidate_id': 'c1', 'distance': 10, 'rank': 3}]
Example 2
Input: rank_nearest_neighbors([{'target_id': 't1', 'f1': 1, 'f2': None, 'f3': 4}], [{'candidate_id': 'c1', 'f1': 1, 'f2': 10, 'f3': None}, {'candidate_id': 'c2', 'f1': 3, 'f2': None, 'f3': 8}, {'candidate_id': 'c3', 'f1': None, 'f2': None, 'f3': None}])
Output: [{'target_id': 't1', 'candidate_id': 'c1', 'distance': 0, 'rank': 1}, {'target_id': 't1', 'candidate_id': 'c2', 'distance': 10, 'rank': 2}, {'target_id': 't1', 'candidate_id': 'c3', 'distance': None, 'rank': 3}]
Example 3
Input: rank_nearest_neighbors([{'target_id': 't1', 'f1': 0}], [{'candidate_id': 'a', 'f1': 1}, {'candidate_id': 'b', 'f1': -1}, {'candidate_id': 'c', 'f1': 2}, {'candidate_id': 'd', 'f1': 3}, {'candidate_id': 'e', 'f1': 4}, {'candidate_id': 'f', 'f1': 5}])
Output: [{'target_id': 't1', 'candidate_id': 'a', 'distance': 1, 'rank': 1}, {'target_id': 't1', 'candidate_id': 'b', 'distance': 1, 'rank': 2}, {'target_id': 't1', 'candidate_id': 'c', 'distance': 4, 'rank': 3}, {'target_id': 't1', 'candidate_id': 'd', 'distance': 9, 'rank': 4}, {'target_id': 't1', 'candidate_id': 'e', 'distance': 16, 'rank': 5}]
Hints
Hint 1
Consider what happens when comparing two records that have no overlapping non-null features – how should distance be defined?
Hint 2
For each target, you need to compute distance to every candidate, then select the 5 smallest. What data structure helps efficiently maintain top-k elements?
Hint 3
When sorting distances, remember that None should sort after all numeric values. Python's sort can handle this with a tuple key where the first element indicates whether the value is None.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires computing pairwise distances between two datasets and selecting the top matches for each query record.
The algorithm works as follows:
-
For each target record, extract the feature column names (all keys except the ID field).
-
For each candidate record, compute the distance to the current target:
- Iterate through all feature columns
- Collect pairs where both target and candidate have non-
Nonevalues - If at least one valid pair exists, compute MSE as the average of squared differences
- If no valid pairs exist (all features are
Nonein at least one record), set distance toNone
-
Sort candidates by distance for this target:
- Numeric distances are sorted in ascending order (smallest first)
Nonedistances are placed after all numeric values- When distances are equal, maintain the original candidate order (stable sort)
-
Select the top 5 candidates (or fewer if less than 5 candidates exist) and assign ranks 1 through 5.
-
Append results for this target to the output list.
Why It Works
- Exhaustive comparison: Every target is compared against every candidate, ensuring no potential matches are missed.
- Pairwise feature handling: By computing MSE only over shared non-
Nonefeatures, we avoid penalizing missing data and keep distances comparable across pairs with different amounts of missing values. - Correct ordering: The sort key
(x[1] is None, x[1] if x[1] is not None else 0)ensures numeric distances sort beforeNone, and equal distances maintain input order due to Python's stable sort. - Top-k selection: Slicing the sorted list at position 5 correctly returns the 5 smallest distances or all candidates if fewer than 5 exist.
Complexity
Let T = number of targets, C = number of candidates, and k = number of features.
- Time: O(T × C × k) to compute all distances, plus O(T × C log C) for sorting. The sorting can be optimized to O(T × C log 5) using
heapq.nsmallest, though the tie-breaking behavior remains identical with stable sorting. - Space: O(C) working memory per target for the distance list, plus O(5T) for the output (at most 5 matches per target).
Solution
from typing import List, Dict
def rank_nearest_neighbors(target_rows: List[Dict], candidate_rows: List[Dict]) -> List[Dict]:
"""
For each target row, find the 5 closest candidate rows using MSE distance.
Distance is computed only over features present (non-None) in both records.
If no features overlap, distance is None.
No feature scaling is applied.
"""
result = []
for target in target_rows:
target_id = target['target_id']
# Identify feature columns (everything except the ID field)
feature_cols = [k for k in target.keys() if k != 'target_id']
distances = []
for candidate in candidate_rows:
candidate_id = candidate['candidate_id']
# Find features that are non-None in both records
valid_pairs = []
for col in feature_cols:
t_val = target.get(col)
c_val = candidate.get(col)
if t_val is not None and c_val is not None:
valid_pairs.append((t_val, c_val))
# Compute MSE over valid features
if len(valid_pairs) == 0:
distance = None
else:
mse = sum((t - c) ** 2 for t, c in valid_pairs) / len(valid_pairs)
distance = mse
distances.append((candidate_id, distance))
# Sort: numeric distances ascending, None values last, stable for ties
distances.sort(key=lambda x: (x[1] is None, x[1] if x[1] is not None else 0))
# Select top 5 matches
top_matches = distances[:5]
for rank, (candidate_id, distance) in enumerate(top_matches, start=1):
result.append({
'target_id': target_id,
'candidate_id': candidate_id,
'distance': distance,
'rank': rank
})
return result