progress

~/problems / Heaps / Heaps and priority queues

The k smallest values with heapq

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Write k_smallest(nums: list[int], k: int) -> list[int] that returns the k smallest values of nums in ascending order, using Python's heapq module.

k_smallest([7, 2, 9, 2, 5], 3)   # [2, 2, 5]   (duplicates count separately)
k_smallest([4, -1, 3], 5)        # [-1, 3, 4]  (k is bigger than the list: return everything)
  • k == 0 or an empty list gives []. Values may be negative or repeat.
  • Don't modify nums.

Two good approaches: heapq.heapify a copy and heappop k times, or keep a max-heap of size k (store negated values). Sorting also works, but the point is to practise the heap.

⭐ Bonus: a speed test with a million values and k = 1000 earns a star in O(n + k log n) or O(n log k). Scanning for the minimum k times is O(n·k).

Show hint

heapify builds a min-heap in O(n), and each heappop hands you the next-smallest value in O(log n).

Topic: Heaps and priority queues. heapq: top-k, k-way merge, two heaps for a running median.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc