KatInterview

Lowest K Values in Ascending Order with Duplicates

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapsortingselection

Last updated

Select the k smallest values from an unsorted integer list, keeping duplicates and returning them sorted ascending, which tests heap, sorting and selection trade-offs.

Lowest K Values

You are given a list of integers values and a non-negative integer count. Produce the count smallest entries of values, arranged from smallest to largest.

Treat values as a multiset: if a number appears several times, each occurrence is a separate entry and competes for a place on its own. If some copies of a number fall within the count smallest entries, all of those copies must appear in the result. When several equal numbers straddle the cutoff, only as many copies as needed to reach exactly count entries are included (since equal numbers are indistinguishable, the output is the same regardless of which copies are chosen).

Input

  • values: a list of integers. It may contain negative numbers, zero, positive numbers, and repeated values. The list is not sorted.
  • count: a non-negative integer, the number of entries to return.

Output

A list of exactly count integers in non-decreasing (ascending) order, consisting of the count smallest entries of values.

Special cases

  • If count is 0, return an empty list.
  • If count equals len(values), return the whole list sorted ascending.
  • If all entries are equal, return count copies of that value.

Constraints

  • 0 <= count <= len(values) <= 1,000,000
  • -10^9 <= values[i] <= 10^9

Think about how your approach behaves in terms of time and memory when count is much smaller than len(values), and when it is close to it.

Examples

Example 1

Input: lowest_k_values([7, 10, 4, 3, 20, 15], 3)

Output: [3, 4, 7]

Example 2

Input: lowest_k_values([5, 2, 2, 8, 1, 5], 4)

Output: [1, 2, 2, 5]

Hints

Hint 1

The answer is a multiset: after you decide which entries belong, sort them. Sorting the whole list and slicing the first `count` items is a valid baseline.

Hint 2

To avoid sorting everything when `count` is small, keep a bounded collection of the best `count` entries seen so far, where you can quickly find and remove the largest one.

Hint 3

Python's `heapq` is a min-heap, so store negated numbers to simulate a max-heap. Only replace the top when a new value is strictly smaller than the current largest kept value, then sort the kept entries at the end.