Deduplicate a Retrieval Result List
Problem Statement
A retrieval index built from augmented or near-duplicate images returns the same underlying item under several ids. Collapse the ranked list to unique items — keeping each item's best (earliest) position — then take the top-K.
Background
Given a ranked list of (item_id, score) results (best first) where item_id may repeat, produce the deduplicated top-K: for each distinct item_id, keep only its first occurrence (highest rank), preserve the original order, and return the first K ids. This mirrors post-processing a retrieval system before showing results to a user, so the same photo does not fill the page.
Your Task
Implement:
def dedup_topk(results, k):
- results: list of (item_id, score) tuples, already sorted best-first.
Return the list of the first K distinct item ids in order.
Input Format
- results: list of (item_id, score).
- k (int).
Output Format
- A list of item ids (length min(K, num_distinct)).
Sample
print(dedup_topk([(5, 0.9), (5, 0.8), (3, 0.7), (2, 0.6)], 2))
Output:
[5, 3]
Example
print(dedup_topk([(5, 0.9), (5, 0.8), (3, 0.7), (2, 0.6)], 2))
[5, 3]
- Input:
resultsis a ranked list of four (id, score) pairs, best first: ranks to hold ids with scores .kis how many distinct items to show. - Duplicates: id appears at rank and rank . Both are the same underlying photo, so only its best position (rank , score ) counts; the rank- copy is discarded.
- Collapsed ranking: after removing repeats the distinct items, in their original order, are . Three distinct items exist, so the answer has length .
- Output: the top of that collapsed list is
[5, 3]. Item is genuinely distinct but falls just outside the cut. - Notice: a naive top-2 of the raw list would be , showing the same photo twice. With
kthe result would be , shorter than because only three distinct ids exist. Scores never decide anything here; the list order already encodes rank.
Constraints
0 <= len(results) <= 100000,k >= 0.- Keep each item's earliest occurrence; preserve order.
- Return at most
Kids.