Combine keyword and vector scores with min-max normalization

BM25 scores can be 0 to 30 while cosine similarities sit between -1 and 1. Adding them raw lets one retriever drown out the other, so hybrid search rescales each score list first.

Write hybrid_rank(bm25, dense, alpha). Both are 1-D arrays of length n with scores for the same n documents.
- Min-max normalize each list to [0, 1]: (s - min) / (max - min). If max == min, that list becomes all zeros.
- Fused score = alpha * dense_norm + (1 - alpha) * bm25_norm.
Return (order, scores): order is the list of document indices sorted by fused score descending (ties: lower index first), and scores is the fused score list in original document order, each rounded to 6 decimals.

Signaturedef hybrid_rank(bm25, dense, alpha)

Example

bm25 = [10, 0, 5], dense = [0.1, 0.9, 0.5], alpha = 0.5. Normalized bm25 = [1, 0, 0.5], dense = [0, 1, 0.5], fused = [0.5, 0.5, 0.5], so order = [0, 1, 2].

Understand the idea

Keyword scores like BM25 might run from 0 to 30 while cosine similarity stays between -1 and 1. If you add them raw, the bigger numbers win no matter what weight you choose. Min-max scaling squeezes each list onto 0 to 1 first, so alpha really controls the balance. Worked example: bm25 = [8, 2, 4], dense = [0.2, 0.8, 0.6], alpha = 0.7. bm25 scaled: (s - 2) / 6 = [1, 0, 0.3333]. dense scaled: (s - 0.2) / 0.6 = [0, 1, 0.6667]. Fused = 0.7 * dense + 0.3 * bm25 = [0.3, 0.7, 0.4667 + 0.1 = 0.5667]. Order = [1, 2, 0]. Rule: norm(s) = (s - min) / (max - min), or all zeros if max equals min; fused = alpha * dense_norm + (1 - alpha) * bm25_norm; sort indices by fused descending with lower index first on ties; return scores in the original document order, rounded to 6 decimals. Used in hybrid RAG retrieval where lexical and semantic search are blended.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplehybrid_rank([10, 0, 5], [0.1, 0.9, 0.5], 0.5)
  • Sample 2: dense heavyhybrid_rank([22.0, 3.5, 8.0, 0.0], [0.2, 0.8, 0.75, 0.3], 0.8)
  • Test 3: flat bm25hybrid_rank([4.0, 4.0, 4.0], [0.3, -0.1, 0.6], 0.3)
  • Test 4: keyword onlyhybrid_rank([1.0, 7.0, 3.0], [0.9, 0.1, 0.5], 0.0)