KatInterview

Filter and Sort Items by Embedding Similarity Score

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashingarrayssortingfiltering

Last updated

Tests vector scoring with dot products, stable sorting with tie-breaking, and set-based filtering of excluded indices.

You're building a recommendation engine that scores candidate items against a user profile. Both the user and each item are represented as vectors of the same length. The relevance score between the user and an item is computed as the dot product of their vectors.

Write a function that computes the score for each item, filters out items that should be excluded, and returns the remaining item indices ordered by their scores.

Task

Given:

  • user_vector: a list of integers representing the user's profile
  • item_vectors: a list where item_vectors[i] is the vector for item i
  • exclude_indices: a list of item indices that should not appear in the output

Return a list of item indices (positions in item_vectors) sorted by their scores in descending order. When two items have identical scores, the item with the smaller index should appear first.

Scoring

The score for item i is calculated as:

score(i) = sum(user_vector[j] * item_vectors[i][j] for all j)

This is the standard dot product of the two vectors.

Constraints

  • 1 ≤ len(user_vector) ≤ 128
  • All vectors in item_vectors have the same length as user_vector
  • 1 ≤ len(item_vectors) ≤ 10,000
  • All vector components are integers in the range [-1000, 1000]
  • 0 ≤ len(exclude_indices) ≤ len(item_vectors)
  • All values in exclude_indices are valid indices into item_vectors (between 0 and len(item_vectors) - 1)
  • All values in exclude_indices are distinct

Examples

Example 1

Input: filter_and_sort_by_score([1, 2], [[3, 0], [1, 1], [0, 2], [-1, 4]], [])

Output: [3, 2, 0, 1]

Example 2

Input: filter_and_sort_by_score([1, 2], [[3, 0], [1, 1], [0, 2], [-1, 4]], [2, 0])

Output: [3, 1]

Example 3

Input: filter_and_sort_by_score([2, -1, 0], [[1, 1, 5], [0, 3, 1], [2, 4, -3], [-1, -5, 7]], [3])

Output: [0, 2, 1]

Hints

Hint 1

Convert the exclusion list to a set for efficient lookups during iteration.

Hint 2

Use a composite sorting key that handles both score ordering and tie-breaking in a single sort operation.

Hint 3

Negate the score in your sorting key to sort descending while keeping indices ascending for ties.