KatInterview

Top K Highest Scores in Descending Order

Heaps, Sorting & SearchAuto-graded · 17 test cases

Last updated

Select the k greatest values from an unsorted integer list, duplicates included, returned from largest to smallest, ideally in O(n log k) time using a bounded min-heap.

Top K Highest Scores

You are given an unsorted list of integers scores and a positive integer k. Return the k greatest values in the list, ordered from largest to smallest.

Rules

  • Duplicates count separately. If a value appears several times, each occurrence is a separate candidate. For example, if the two largest entries are both 5, the result contains 5 twice.
  • Do not remove duplicates from the input.
  • The result must have exactly k elements and be sorted in descending (non-increasing) order.
  • Negative numbers are ordinary values and are compared normally.
  • If k equals the length of the list, return the entire list sorted in descending order.
  • Do not modify the input in a way that affects the returned value; only the returned list is checked.

Sorting the entire list works, but a stronger answer avoids a full sort when k is much smaller than the list length by keeping only a bounded collection of the best candidates seen so far.

Constraints

  • 1 <= k <= len(scores)
  • 1 <= len(scores) <= 10^6
  • -10^9 <= scores[i] <= 10^9

Examples

Example 1

Input: top_k_scores([3, 2, 1, 5, 6, 4], 2)

Output: [6, 5]

Example 2

Input: top_k_scores([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)

Output: [6, 5, 5, 4]

Hints

Hint 1

You only need to remember the k best values seen so far, not the whole array. Which structure lets you quickly find and discard the weakest of those k?

Hint 2

Keep a min-heap of size k. Its root is the smallest of your current top k, so a new value only matters if it is strictly larger than the root.

Hint 3

A heap's internal order is not sorted order. After scanning everything, sort the k remaining values in descending order before returning them.