Skip to contentKEEP THE CRAFTTHE SANCTUARY

Keep the K Smallest Stream Values

Keep only k candidates in a heap while reading the values, then return the k smallest in order.

The problem

Implement k_smallest_values(values, k). Read the values one by one and return the k smallest of them in ascending order. Repeated values count separately, so [2, 1, 2, 1] with k = 3 gives [1, 1, 2]. If k is 0, return []. You may assume 0 <= k <= len(values). Keep at most k values in memory while you read, instead of sorting the whole list.

Starter code

def k_smallest_values(values, k):
    pass

Public examples

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

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

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