Iteration

K Smallest Elements

Given an array arr and an integer k, return the k smallest elements in the array. Note that "elements" is plural.

You can return the elements in any order, and 0 < k <= len(arr).

First Few Test Cases:

The standard interview solution is to add all the elements to a Heap, and then pop the Heap k times. Every time you pop an element, you add it to the answer, since it's one of the k smallest elements.

Here's the code:

Time Complexity O(n+klogn)O(n + k \log n). Turning the array into a heap takes O(n) time. We then pop from the heap kk times, and each pop takes logn\log n time.

Space Complexity O(1)O(1). You don't end up using any extra space in the above solution. You're just transferring elements from arr into answer.

That was the standard interview solution, but it's actually not optimal. Here's the optimal solution, which probably isn't needed for an interview. It uses QuickSelect and takes O(n) time.

A 3rd solution is to use Counting Sort to sort the elements and then take the top kk, but the stars really need to align for it to be optimal, and it's advanced knowledge. Counting Sort only works in certain problems, and it takes O(n+maxmin)O(n + \max - \min) time in general. It's only O(n)O(n) if you know the range of elements is O(n)O(n) too, like counting the top frequencies of elements in an array.

Mark as Completed:
Submits:
kSmallestElements
Test your code to get an output here!
kSmallestElements(
)
Test your code to get an output here!