Filter and Sort Items by Embedding Similarity Score
Arrays & HashingAuto-graded · 18 test casesLast 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 profileitem_vectors: a list whereitem_vectors[i]is the vector for itemiexclude_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_vectorshave the same length asuser_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_indicesare valid indices intoitem_vectors(between0andlen(item_vectors) - 1) - All values in
exclude_indicesare 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires three operations: computing similarity scores, filtering excluded items, and sorting with proper tie-breaking.
Step 1: Compute scores efficiently
For each item not in the exclusion list, calculate its dot product with the user vector. The dot product is the sum of element-wise products: sum(user_vector[j] * item_vectors[i][j]) for all positions j.
Step 2: Filter excluded items
Convert exclude_indices to a set first. This allows O(1) membership checks instead of O(n) list scans during iteration. Skip any item whose index appears in this set.
Step 3: Sort with correct tie-breaking
We need items sorted by score from highest to lowest, but when scores are equal, smaller indices should come first. A clean approach uses tuple sorting: create a key (-score, index) for each item and sort these tuples in ascending order.
Python compares tuples element-by-element. The negative score ensures higher scores come first (because a more negative number is smaller). The positive index ensures smaller indices come first when scores are equal. One ascending sort achieves both requirements without needing reverse=True or custom comparators.
Why It Works
All inputs are integers, so dot products are exact integers—no floating-point rounding affects the ordering. Two items tie only when their actual scores are mathematically equal.
The tuple-based sorting key directly encodes the required ordering: for items a and b, tuple (-score_a, a) precedes (-score_b, b) exactly when score_a > score_b, or when scores are equal and a < b. Since indices are distinct, every comparison has a definite outcome.
Complexity
Let N = len(item_vectors), d = len(user_vector), and M be the number of non-excluded items.
Time Complexity: O(N·d + M log M)
- Computing all dot products: O(N·d)
- Building the exclusion set: O(len(exclude_indices))
- Sorting scored items: O(M log M)
With the given constraints (N ≤ 10,000, d ≤ 128), the scoring phase dominates.
Space Complexity: O(M + len(exclude_indices))
- Exclusion set storage
- List of scored items and output
Solution
def filter_and_sort_by_score(user_vector, item_vectors, exclude_indices):
exclude_set = set(exclude_indices)
scored = []
for i, vec in enumerate(item_vectors):
if i in exclude_set:
continue
s = sum(u * x for u, x in zip(user_vector, vec))
scored.append((-s, i))
scored.sort()
return [i for _, i in scored]