Challenge: Find k Smallest Elements in an Array
Given an array and a number "k", write a function that returns the first "k" smallest elements using a min-heap.
We'll cover the following
Problem Statement
Implement a function findKSmallest(arr,k)
that takes an unsorted integer array as input and returns the “k” smallest elements in the array using a min-heap. The minHeap
class is prepended to this exercise so feel free to use it! Have a look at the illustration given for a clearer picture of the problem.
Input
An array containing integers
Output
Returns an integer array that contains the first smallest elements from the given array.
Sample Input
arr = [9,4,7,1,-2,6,5] k = 3
Sample Output
[-2,1,4]
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.