Coding Round: Merge Top-k From Sorted Shards, Then Fuse Two Rankings by Place
Two coding-round ideas in plain words. Merging three sorted shard lists by sorting all 11 rows gives five rows but only three documents; a small next-best pile with a seen set gives five documents after looking at 7 rows. Then why adding raw scores copies one judge, and how rank fusion lifts d4 to the top by a hair.
What you will learn
- Ask the four questions before merging ranked lists: sorted, repeats, ties, empty lists
- See why sort-everything-and-cut returns 5 rows but only 3 documents
- Explain the next-best pile (a heap): one row per list, take the best, refill, skip what you've seen
- Explain why adding raw scores lets one ranking decide, and what reciprocal rank fusion gives up
Before you start
- Hybrid Search: BM25 Plus Dense Embeddings
- Basic Python lists and sorting
This one comes from a coding round, but the ideas matter more than the syntax. Idea one: several sorted lists arrive from different shards, and you want the best five overall. Idea two: two rankings of the same documents, and you want one ranking out of them. All the examples here are small and synthetic, made up for illustration.
Three stacks of exam papers
Three teachers each hand you a stack of exam papers. Every stack is sorted, highest mark on top, and you need the top five overall. You don't shuffle everything together. You look at the top sheet of each stack, take the highest, and that stack shows you its next sheet. So you only ever compare three sheets.
In a search system, those stacks are shards, and each shard sends back its own sorted list. Before you start, ask four questions:
- Is every list truly sorted?
- Can one document sit in two lists?
- If scores tie, who goes first?
- What if a list is empty?
Asking these out loud is part of the score. The interviewer wants to see that you know where the edge cases are before you write a line.
The simple answer goes wrong
The simple answer: pour all the lists into one pile, sort it, cut at five. With three synthetic lists, eleven rows in all, here is what that gives:
naive top 5
d4 0.95000
a7 0.91000
c2 0.88000
c2 0.84000
d4 0.80000
You asked for five documents and got three. c2 and d4 sit in two lists, and each copy took a seat. f9 and g6 should have made it, and they're left outside. So sorting everything does extra work, and here it's also wrong.
The next best pile
Now the better idea. Each list puts only its top row into a small pile. You take the best one from the pile, and the list it came from slides up its next row, so the pile always holds one row per list. A short note beside the answer tracks the documents you've already taken, so a repeat is skipped.
Walk through it. The best row in the pile is d4 at 0.95, so it goes into the answer, and its list slides up g6. When c2 shows up a second time, it's skipped. Then three rows tie at 0.80, so you pick one fixed rule (for example by name) and use it every time. d4's second copy comes first and gets skipped, then f9 and g6 take the last two seats.
heap merge top 5
d4 0.95000
a7 0.91000
c2 0.88000
f9 0.80000
g6 0.80000
items touched: 7 of 11
Five documents, and we stopped after looking at seven of the eleven rows. In a bigger synthetic run with 200,000 rows and no repeats, the merge looked at just 10 rows and gave the same answer as sorting everything. The run also printed timings (sorting everything 96.8 ms, the heap merge 0.05 ms), but those vary between runs, so quote the shape, not the numbers.
If you want to write it down, the steps fit in a short sketch. This is an illustration written for this article, not the lecture's code:
# Sketch only: lists are sorted best-first, rows are (doc, score)
import heapq
def top_k(lists, k):
pile = [(-rows[0][1], rows[0][0], i, 0) for i, rows in enumerate(lists) if rows]
heapq.heapify(pile) # ties break by doc name: one fixed rule
seen, answer = set(), []
while pile and len(answer) < k:
neg, doc, i, j = heapq.heappop(pile)
if doc not in seen:
seen.add(doc)
answer.append((doc, -neg))
if j + 1 < len(lists[i]):
nxt_doc, nxt_score = lists[i][j + 1]
heapq.heappush(pile, (-nxt_score, nxt_doc, i, j + 1))
return answer
Say the assumption out loud: this only stays cheap because the lists arrive sorted. Somebody paid for that sort earlier, on each shard.
Two judges, two scales
Second idea. A keyword search and a meaning search give you two rankings of the same documents. Picture two judges at a baking contest: one scores in the twenties, the other scores below one. The obvious move is to add each document's scores:
sum of raw scores, top 3
d1 24.40000
d2 22.28000
d3 19.00000
lexical alone, top 3: ['d1', 'd2', 'd3']
That's exactly the first judge's own top three. The second judge had no say, and d4, the second judge's favourite, doesn't make the top three. The judge with the big scale decides everything. You could rescale, but the spread shifts between searches.
Compare places, not scores
So compare places instead. Each list becomes first, second, third, and the scale disappears. Each place earns a small vote of 1 / (60 + place), and the votes add up. The 60 keeps the gaps gentle.
rrf k=60, top 5
d4 0.03202
d2 0.03200
d1 0.03178
d5 0.03151
d6 0.03030
d4 is fourth with one judge and first with the other, and rises to the top. d3 drops out of the top five, because only one judge knows it. Two honest notes: d4 wins by a hair (0.03202 against 0.03200), so don't call it a strong win. And this method throws away how far ahead a document was, because only the place counts. This is reciprocal rank fusion; the full treatment with BM25 and embeddings is in Hybrid Search: BM25 Plus Dense, Merged With RRF.
Talking it through
- Questions: sorted? repeats? ties? empty lists?
- Simple answer and its problem: "I could sort everything, but repeats would take seats, and I'd read every row."
- Better idea: one row per list in a small pile, take the best, refill, skip what I've seen, stop at five.
- Assumption: the lists arrive sorted.
- Rankings: "The scores sit on different scales, so I'll combine places, and I give up how far ahead anything was."
Follow-ups and a simple rubric
These answers are design guidance, not measured:
- One shard is slow? Set a time limit, merge what arrived, and mark the answer as partial.
- Lots of repeats? Each shard has to send more than five, or you can run short.
- Why 60? It's a common default, so test it on your own data.
- How would you catch this breaking again? Keep a slice of exact-code questions in your evaluation set, and compare before and after each change.
| Level | What it sounds like |
|---|---|
| Weak | Sorts everything and doesn't notice the repeats |
| Solid | Asks the questions, explains the pile, combines places correctly |
| Strong | Also states the sorted assumption and the tie rule, and names what rank fusion gives up |
The rubric is a suggestion, not any company's official sheet.
Recap
| Idea | What to remember |
|---|---|
| Sort and cut | 5 rows but only 3 documents |
| Next best pile | 5 documents after looking at 7 of 11 rows; sorted lists assumed |
| Raw scores | The big scale wins |
| Rank fusion | Places, not scores; d4 on top by a small margin |
Try it yourself
On paper, use 10 in place of 60. Work out the votes for d4 (fourth and first) and d2 (second and third). Who comes first now?
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)Related posts
The ML Engineer Interview Loop: Five Rounds, What Each One Looks For, and a Simple Rubric
The rounds you go through for one ML engineer job: recruiter screen, coding, ML depth, ML system design and behavioural. What each round looks for, the follow-up it brings, and a four-check rubric for your own answers.
The Answer Framework for Technical Interviews: Five Moves, Scored Out of 24
Good interview answers share one shape: a 30-second answer, the mechanism, the trade-off, the metric and the failure test. Worked on one question about a batch job starving everyone else, with a 24-point example rubric.
From Symptom to Pattern: How to Answer "Which Pattern Would You Use?" in an Interview
Start from what you can see, not from the pattern you know. A four-step rule (symptom, cost, metric and failure test, ship first), a symptom table, one worked answer for 429s at peak, and the trap of using a prompt as a lock.
The ML System Design Framework: Eight Steps, in Order, on a Spam Filter
One repeatable route through any ML system design question: goal, metric, data, features, model, serving, monitoring and failure. Worked on an email spam filter, with the follow-ups and a three-check rubric.