PIXELBANKv9.1.0
Menu

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:

Input:
print(dedup_topk([(5, 0.9), (5, 0.8), (3, 0.7), (2, 0.6)], 2))
Output:
[5, 3]
Reasoning:
  • Initialize an empty set to track seen items and an empty list for the result, since we need to preserve the first occurrence of each unique ID.
  • Process the first result (5,0.9)(5, 0.9): ID 55 is not in the seen set, so add 55 to the seen set and append 55 to the result list; the result is now [5][5].
  • Process the second result (5,0.8)(5, 0.8): ID 55 is already in the seen set, so skip this entry to avoid duplicates.
  • Process the third result (3,0.7)(3, 0.7): ID 33 is not in the seen set, so add 33 to the seen set and append 33 to the result list; the result is now [5,3][5, 3].
  • The result list length is now 22, which matches the target K=2K=2, so stop processing further items (skipping (2,0.6)(2, 0.6)).
  • The final output is [5, 3]

Constraints:

  • 0 <= len(results) <= 100000, k >= 0.
  • Keep each item's earliest occurrence; preserve order.
  • Return at most K ids.
🔒

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

0/0
Run code to see test results.
Deduplicate a Retrieval Result List - Medium | PixelBank