KatInterview

Rank Nearest Neighbors by Mean Squared Error

Arrays & HashingAuto-graded · 17 test cases
EasyAuto-gradedArrays & Hashingsimilaritydistance-metricsranking

Last 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 record
    • f1, f2, ..., fk (float or None): 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 record
    • f1, f2, ..., fk (float or None): 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-None features be the set where target[feature] is not None AND candidate[feature] is not None
  • MSE = (sum of squared differences) / (count of shared features)
  • If no features are shared (all are None in at least one record), the distance is None

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 identifier
  • candidate_id (string): the matched candidate identifier
  • distance (float or None): the computed MSE distance
  • rank (int): rank from 1 to 5, where 1 is the closest match

Ordering and Tie-Breaking:

  • Numeric distances are ordered from smallest to largest
  • None distances 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.