All problems
EasyRetrieval & Rankingv2026-06-30

Retrieval & Ranking ยท Easy

Top-K Heap

Select highest-scoring items efficiently with deterministic heap ordering.

Task

Implement top_k_heap(scores: list[float], k: int) -> list[int]. Return the indices of the highest-scoring items by maintaining a bounded min-heap.

Requirements

  • scores contains finite numeric values and k is a non-negative integer.
  • Return at most min(k, len(scores)) original indices.
  • Rank selected indices by descending score.
  • When scores tie, rank the smaller original index first.
  • Use a heap containing at most k candidates while scanning scores; do not sort the entire input.
  • After selection, sort only the retained candidates into the required output order.
  • Return an empty list when k is zero or scores is empty.
  • When k is at least the input length, return every index in deterministic rank order.
  • Do not mutate scores.

Example

top_k_heap([0.4, 0.9, 0.9, 0.2, 0.7], 3)
# [1, 2, 4]
solution.pySign in to save
Public tests run locally in your browser.
Run your code to see public test results.