Skip to main content

Given a tokenised query and a small list of tokenised documents, score each document with BM25, using k1 = 1.5 and b = 0.75. For example, with the documents cat sat mat, dog sat and cat cat ran far away, the query cat should score the third document highest (about 0.58), the first next (about 0.49) and the second 0.

Coding rounds · Intermediate 3

Short answer

For each query term found in a document, add idf times a saturating term-frequency part: tf * (k1 + 1) / (tf + k1 * (1 - b + b * doc_len / avg_len)). Idf is log((N - df + 0.5) / (df + 0.5) + 1). Precompute document frequencies and lengths once. Cost is O(documents times query terms).

Deeper answer

Clarify first: the documents and the query are already tokenised the same way. The parameters are k1, usually 1.2 to 2.0, and b, usually 0.75.

Precompute three things: N, the number of documents; df[t], the number of documents that contain term t; and avg_len, the mean document length. For each document and each query term in it, with tf as the count of the term in that document, add idf * tf * (k1 + 1) / (tf + k1 * (1 - b + b * doc_len / avg_len)). The idf I use is log((N - df + 0.5) / (df + 0.5) + 1), which is never negative.

The tf part saturates: it can never be more than k1 + 1 times the idf, so repeating a word many times adds little. The b part normalises for length, so long documents are not favoured only for being long. Test with a hand calculation on three tiny documents. Interviewers watch for df counted as total occurrences, and for a negative idf on very common terms.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Hybrid search, reranking and filters

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.