Skip to content

< all problems05 · Level 02, Search

Build Top-K Semantic Search

easy · implement · Embeddings & Retrieval

Implement top_k_search(query, documents, k): a list of (index, score) pairs for the k most similar documents, best first. cosine_similarity from the previous problem is already defined for you.

  1. Sort by score descending, ties broken by the lower index.
  2. If k exceeds the number of documents, return all of them. Don't pad, don't raise.
  3. k <= 0 returns an empty list.
  4. Scores are plain floats.