v9.1.1
Menu

Deduplicate a Retrieval Result List

mediumPRORetrieval & Zero-Shot TransferVision-Language ModelsVLM 1: Vision-Language Models

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

Input
print(dedup_topk([(5, 0.9), (5, 0.8), (3, 0.7), (2, 0.6)], 2))
Output
[5, 3]
Reasoning
  • Input: results is a ranked list of four (id, score) pairs, best first: ranks 11 to 44 hold ids 5,5,3,25, 5, 3, 2 with scores 0.9,0.8,0.7,0.60.9, 0.8, 0.7, 0.6. k =2= 2 is how many distinct items to show.
  • Duplicates: id 55 appears at rank 11 and rank 22. Both are the same underlying photo, so only its best position (rank 11, score 0.90.9) counts; the rank-22 copy is discarded.
  • Collapsed ranking: after removing repeats the distinct items, in their original order, are 5,3,25, 3, 2. Three distinct items exist, so the answer has length min⁡(K,3)=min⁡(2,3)=2\min(K, 3) = \min(2, 3) = 2.
  • Output: the top 22 of that collapsed list is [5, 3]. Item 22 is genuinely distinct but falls just outside the cut.
  • Notice: a naive top-2 of the raw list would be [5,5][5, 5], showing the same photo twice. With k =5= 5 the result would be [5,3,2][5, 3, 2], shorter than KK 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 K ids.

More from VLM 1: Vision-Language Models

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.