A practice prompt we wrote. No company or candidate report names it, so it carries no company tag.
How to answer
“Fast enough” is a number the interviewer has and you don’t yet. Get it, make exact search fast, and say where exact stops being enough.
- Ask for the sizes and the budget. How many vectors, what dimension, how many queries at once, what
k, what latency target. Do the memory arithmetic aloud:n * d * 4bytes in float32 tells you whether the corpus fits in memory. - Normalize the corpus once, when you build the index. Then cosine similarity is a dot product. Reject zero vectors, whose cosine is undefined. Normalizing the query changes the scores, not the ranking; say so.
- Score with a matrix multiply. Stack the queries into a matrix and let one BLAS call score a block of the corpus against all of them. No Python loop over vectors.
- Select, don’t sort.
np.argpartitionfinds the topkin linear time, then sort only thosek. In plain Python,heapq.nlargestkeeps a heap of sizek:O(n log k). - Block over the corpus to bound memory. Score one block, keep its top
k, merge with the running topk. The score matrix never exceeds queries times block size. - State the complexity, then prove it right. Scoring is
O(q * n * d)and dominates the operation count; selection isO(q * n), but BLAS can make the multiply faster than the selection, so time both. Check against a brute-force full sort on small random data first. - Say when to stop. If exact search misses the budget, go approximate (quantized vectors, clustering or a graph index from a library) and measure recall against the exact results you just built.
The trap is a full argsort of every score. Measure it: it can cost more than the multiply that produced the scores.
Follow-ups
What the interviewer may ask next, once your first answer is on the table.
- The vectors no longer fit in memory. What changes, and what stays the same?
- Exact search misses the latency budget by a wide margin. What do you give up to meet it, and how do you measure what you gave up?
- Two documents have exactly the same score at the cutoff. Which one is returned, and does anyone care?
- The customer adds documents all day. How does a new vector get into the index?
Where answers go wrong
- Recomputing both norms for every pair inside a Python loop, instead of normalizing the corpus once and scoring with one matrix multiply.
- Sorting every score to take the first few, when a partial selection does the same job in linear time.
- Reaching for an approximate index before measuring whether exact search already meets the budget.
Answer this in two minutes
Write the answer you would say out loud. The clock starts with your first word.
Model answer
“Let me pin the numbers. You said about 200_000 vectors of dimension 384, batches of queries, k = 10, and results within a request.