Lowest K Values in Ascending Order with Duplicates
Heaps, Sorting & SearchAuto-graded · 22 test casesLast 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
countis0, return an empty list. - If
countequalslen(values), return the whole list sorted ascending. - If all entries are equal, return
countcopies 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The result is the count smallest entries of a multiset, listed in ascending order. There are two reasonable strategies, and the reference solution picks between them based on the size of count relative to the list length n.
- Trivial case. If
count == 0, return[]. - Large
count(2 * count >= n). Sort the entire list and take the firstcountitems. This is correct by definition, and a single call to the built-in sort is very fast whencountis a sizable fraction ofn. - Small
count(2 * count < n). Keep a bounded max-heap of sizecount:- Build a heap from the first
countentries (negated, becauseheapqis a min-heap) usingheapify, which takes O(count). - For each remaining value
v, compare it with the largest kept value (-heap[0]). Ifvis strictly smaller, replace the root with-vusingheapreplace(O(log count)). Otherwise skip it. - At the end, un-negate the heap contents and sort them ascending.
- Build a heap from the first
Why it is correct
Invariant: after processing the first i >= count entries, the heap holds count entries that form the count smallest of those i entries.
- At
i = count, the heap holds exactly those entries, so the invariant holds. - For a new value
vwith current heap maximumm:- If
v >= m, then at leastcountentries are already<= v, sovis not needed. Skipping it keeps the invariant. - If
v < m, thenmis no longer among thecountsmallest, so replacingmwithvrestores the invariant.
- If
Duplicates are handled naturally: copies already inside the heap are separate entries, and skipping an incoming value equal to the root is harmless because swapping equal values would not change the output. The sorting branch is correct by definition, so both branches return identical results.
Complexity
- Sort branch: O(n log n) time, O(n) extra space.
- Heap branch: O(count + (n - count) log count + count log count) = O(n log count) worst case time, O(count) extra space. The heap approach also works on streaming data, since it only needs one element at a time.
Reference solution
import heapq
from typing import List
def lowest_k_values(values: List[int], count: int) -> List[int]:
if count == 0:
return []
n = len(values)
# When count is a large fraction of n, one sort is simplest and fast.
if count * 2 >= n:
return sorted(values)[:count]
# Max-heap (via negation) of the `count` smallest entries seen so far.
heap = [-v for v in values[:count]]
heapq.heapify(heap)
for v in values[count:]:
if v < -heap[0]:
heapq.heapreplace(heap, -v)
return sorted(-v for v in heap)