Return the k smallest elements of the array, sorted ascending. Assume
0 <= k <= len(nums).
kSmallest(nums, k)
Input format: nums | k. Output the k smallest values, sorted, space-separated.
[5, 2, 8, 1, 9], k=3 // → [1, 2, 5]
[4, 3], k=0 // → []
[7], k=1 // → [7]
The simplest approach: sort ascending, take the first k. Works, but like finding a single k-th ranked element, full sorting spends effort ordering elements far outside the k smallest — effort you don't need.
You only need to know which k elements are smallest, and their order among themselves — not the exact order of everything. That suggests tracking a bounded set of candidates instead of fully sorting.
Maintain a max-heap of size k — root is always the largest of the tracked values. Backwards-feeling, but symmetric to the k-largest problem:
The max-heap tracks "who's the weakest candidate I'd throw out if something better shows up" — the largest of the tracked values, hence a max-heap even though the target is the smallest elements overall.
Each heap operation costs O(log k), across n elements giving O(n log k) — cheaper than O(n log n) whenever k is small relative to n.
The heap tracks only k elements — O(k) space instead of a fully sorted O(n) array — but gives no information about anything outside those k. Since the problem only asks for the k smallest, that's exactly the information you don't need.
import heapq
def k_smallest(nums, k):
return sorted(heapq.nsmallest(k, nums))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.