PIXELBANKv9.1.0
Menu

Implement Reciprocal Rank Fusion (RRF) to combine multiple ranked lists.

RRF combines rankings from multiple retrieval systems: RRF(d)=∑r∈R1k+rankr(d)\text{RRF}(d) = \sum_{r \in R} \frac{1}{k + \text{rank}_r(d)}

where k is a constant (typically 60) and rank_r(d) is the 1-based rank of document d in ranking r. Documents not in a ranking are ignored for that ranking.

Input:

  • Line 1: k (constant)
  • Line 2: M (number of rankings)
  • Next M lines: space-separated document IDs (in ranked order)

Output: Document IDs sorted by RRF score (descending), one per line. Break ties by lower ID first.

Example:

Input:
60
2
A B C D
B D A
Output:
A
B
D
C
Reasoning:
  • We start by reading the input values: k=60k = 60 and M=2M = 2 ranked lists.
  • For each document, we calculate the RRF score using the formula: RRF(d)=∑r∈R1k+rankr(d)\text{RRF}(d) = \sum_{r \in R} \frac{1}{k + \text{rank}_r(d)}. For example, RRF(A)=160+1+160+3=161+163\text{RRF}(A) = \frac{1}{60 + 1} + \frac{1}{60 + 3} = \frac{1}{61} + \frac{1}{63}.
  • We calculate the RRF scores for all documents:
    • RRF(A)=161+163\text{RRF}(A) = \frac{1}{61} + \frac{1}{63}
    • RRF(B)=160+2+160+1=162+161\text{RRF}(B) = \frac{1}{60 + 2} + \frac{1}{60 + 1} = \frac{1}{62} + \frac{1}{61}
    • RRF(C)=160+3=163\text{RRF}(C) = \frac{1}{60 + 3} = \frac{1}{63}
    • RRF(D)=160+4+160+2=164+162\text{RRF}(D) = \frac{1}{60 + 4} + \frac{1}{60 + 2} = \frac{1}{64} + \frac{1}{62}
  • We sort the documents by their RRF scores in descending order and break ties by their IDs: RRF(B)>RRF(A)>RRF(D)>RRF(C)\text{RRF}(B) > \text{RRF}(A) > \text{RRF}(D) > \text{RRF}(C), but since RRF(B)\text{RRF}(B) and RRF(A)\text{RRF}(A) are very close, we need to compute them precisely to determine the order, which results in AA having a slightly higher score than BB due to the actual values of 161+163\frac{1}{61} + \frac{1}{63} and 162+161\frac{1}{62} + \frac{1}{61}.

Constraints:

  • k > 0 (typically 60)
  • Rankings may have different lengths
  • Rankings may contain different documents
  • Round RRF scores to 6 decimal places for comparison
🔒

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.
Reciprocal Rank Fusion - Medium | PixelBank