Problems
Loading...
1 / 1

Top-K Recommendations

Recommender Systems
Easy

The final step in most recommender systems is selecting the top-K items to present to a user. Given predicted scores for all items and a set of items the user has already rated, the system must return the K highest-scoring items that the user has not yet seen.

Given a list of predicted scores (one per item), a set of already-rated item indices, and a count K, return the indices of the top-K unrated items sorted by descending score.

Algorithm

  1. Filter out items that appear in the rated set
  2. Sort the remaining items by their predicted score in descending order
  3. Return the indices of the top K items
Loading visualization...

Examples

Input:

scores = [3.5, 1.2, 4.8, 2.1, 5.0], rated_indices = {0, 2}, k = 2

Output:

[4, 3]

Items 0 and 2 are already rated. Among unrated items: item 4 (5.0), item 3 (2.1), item 1 (1.2). Top-2 by score: [4, 3].

Input:

scores = [1.0, 3.0, 2.0], rated_indices = {}, k = 2

Output:

[1, 2]

No items are rated. Sort all by score: item 1 (3.0), item 2 (2.0), item 0 (1.0). Return top-2: [1, 2].

Hint 1

Create a list of (score, index) pairs for items not in rated_indices. Sort by score in descending order. Return the indices of the first K entries.

Hint 2

Use a list comprehension to filter: [(scores[i], i) for i in range(len(scores)) if i not in rated_indices]. Then sort with key=lambda x: -x[0] and slice [:k].

Requirements

  • Exclude all items whose indices appear in rated_indices
  • Sort remaining items by predicted score in descending order
  • Return the indices of the top K items as a list
  • If fewer than K items are unrated, return all unrated item indices

Constraints

  • scores is a non-empty list of floats
  • rated_indices is a set of valid indices
  • 1 <= k <= len(scores)
  • Return a list of integers (item indices)
  • Time limit: 300 ms
Try Similar Problems