Skip to contentKEEP THE CRAFTTHE SANCTUARY

Keep the K Largest Values

Keep the k largest values with a min-heap of size k and return them in ascending order.

The problem

Implement largest_k_sorted(values, k). Return the k largest values from values in ascending order, keeping duplicates. For example, [5, 1, 9, 3, 9, 2] with k = 3 gives [5, 9, 9]. When k is 0, return []. When k is larger than len(values), return every value in ascending order. Scan values once and use only O(k) extra space while scanning.

Starter code

def largest_k_sorted(values, k):
    pass

Public examples

  1. values = [5, 1, 9, 3, 9, 2], k = 3gives[5, 9, 9]
  2. values = [4, 2], k = 0gives[]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.