Pick the highest-scoring movie row by top-k similarity
I was asked this
No reports yet. Sign in to say where you were asked it.
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 moviei(movie IDs are0..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
khighest similarity scores among its distinct movies. If a group has fewer thankdistinct movies, sum all of them. An empty group scores0.
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
kthe same for every group?
What a strong answer covers
- For each group, removes duplicate IDs with a set and takes the
klargest scores withheapq.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
kmovies 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,
klarger than every group and exact ties.
Follow-ups
- Return the top
rrows 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
