Problems › Heaps

K Smallest Elements

Difficulty: Medium · Topic: Heaps

Given an array nums and an integer k, return the k smallest elements in ascending order. A heap of size k (or a partial selection) avoids fully sorting when k is small.

Examples

k_smallest([3,1,2,5,4], 2)
→ [1,2]
k_smallest([5], 1)
→ [5]

Target complexity: time O(n log k), space O(k)

Write your solution in Python and run it against hidden tests right on this page. Progressive hints and Python + C++ reference solutions are included.

Learn the idea first: the lesson for this problem.

More Heaps problems