Skip to main content

Given, for each test question, the ranked list of retrieved ids and the set of relevant ids, compute recall at k and mean reciprocal rank. For example, if the only relevant document is at position 2, recall at 1 is 0, recall at 3 is 1, and the reciprocal rank is 0.5.

Coding rounds · Intermediate 2

Short answer

Recall at k for one query is the number of relevant ids in the first k results divided by the number of relevant ids. Reciprocal rank is 1 over the position of the first relevant result, or 0 if none is found. Average both over all queries. Use a set for the lookup; cost is O(queries times k).

Deeper answer

Clarify first: each query has a ranked list of ids and a set of relevant ids, and a query can have more than one relevant id. Ask what to do with a query that has no relevant ids: skip it and report how many were skipped.

For recall at k, hits = len(set(ranked[:k]) & relevant) and recall = hits / len(relevant). For reciprocal rank, loop with enumerate(ranked, start=1) and return 1 / rank at the first relevant id, or 0 if the loop ends without one. The mean over all queries is MRR.

The two numbers answer different questions. Recall at k says whether the needed chunks were retrieved at all. MRR says how high the first good one is. Test with a relevant item at position 1, at position k + 1 and missing. Interviewers watch for dividing by k, which is precision, for positions that start at 0, and for leaving the missed queries out of the average, which hides the worst failures.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Check whether retrieval works

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.