← Questions

Pick the highest-scoring movie row by top-k similarity

0
NetflixCoding

A coding interview question asked at Netflix. It tests heap, top-k and arrays.

A user just finished a movie they liked. Your recommender already scored every other title for how similar it is to that movie, and the catalog is split into curated groups (rows on the home screen). Pick the row to show first.

Implement:

def highest_scoring_group(similarity: list[float], groups: list[list[int]], k: int) -> int
  • similarity[i] is the similarity between the source movie and movie i (movie IDs are 0..n-1). Scores are floats and may be negative.
  • groups[g] is a list of movie IDs. A movie can appear in several groups.
  • A group's score is the sum of the k highest similarity scores among its distinct movies. If a group has fewer than k distinct movies, sum all of them. An empty group scores 0.

Return the index of the group with the highest score. Break ties by the smaller index. Return -1 if there are no groups.

Constraints: 1 <= n <= 10^5, 0 <= len(groups) <= 10^4, total group memberships up to 10^6, 1 <= k <= 1000. Aim for better than sorting every group.

Example 1

similarity = [0.9, 0.1, 0.4, 0.8, 0.3, 0.75]
groups     = [[0, 1, 2], [3, 5, 4], [1, 4]]
k = 2

Group scores are 0.9 + 0.4 = 1.3, 0.8 + 0.75 = 1.55 and 0.1 + 0.3 = 0.4. Return 1. With k = 1 the scores are 0.9, 0.8 and 0.3, so return 0.

Example 2

similarity = [-0.2, -0.7]
groups     = [[1], [0, 0]]
k = 3

The repeated movie counts once. Scores are -0.7 and -0.2. Return 1.

Clarifying questions

  • Can a movie ID in a group be out of range, and should I raise?
  • Are ties compared on exact float sums, or with a tolerance?
  • Is k the same for every group?

What a strong answer covers

  • For each group, removes duplicate IDs with a set and takes the k largest scores with heapq.nlargest (O(m log k)) or quickselect (O(m)), instead of sorting the group.
  • Sums them, keeps the best score and the smallest index on ties; returns -1 for no groups and scores an empty group 0.
  • Handles negative scores: a group with fewer than k movies sums all of them, so it can beat a larger group (Example 2).
  • Runs in O(total memberships * log k) overall.
  • Tests both examples, duplicate IDs, empty groups, k larger than every group and exact ties.

Follow-ups

  • Return the top r rows in order, not just the best one.
  • Avoid showing the same movie in two of the chosen rows.
  • Similarities change often: keep group scores current without recomputing everything.

Where it's asked

What it tests

heap · top-k · arrays

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding