Challenge: Find the k Smallest Elements in an Array
If you are given an array and any number "k", can you write a code to find the "k" smallest elements using a Min Heap?
We'll cover the following
Problem Statement
In this problem, you have to implement the findKSmallest()
function to take an array as input and find the “k” smallest elements in the array using Min Heap. An illustration is also provided for your understanding.
Function Prototype
int[] findKSmallest(int []arr,int k);
Here, arr is an unsorted integer array and k is an integer.
Output
It returns the integer array containing first k smallest elements from arr
Sample Input
arr = [9,4,7,1,-2,6,5]
k = 3
Sample Output
[-2,1,4]
Explanation
As “k” is 3, we need to find the top 3 minimum elements from the given array. -2 is minimum value in the array, while 1 is the second-minimum, and 4 is the third-minimum.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.