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 == 0or 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).