Challenge 2: Finding “k” Smallest Elements in the Array

Given an array and a number "k," write a function that returns the first "k" smallest elements by using a heap.

Problem statement

Implement a function findKSmallest(int[] arr, int size, int k) that takes an unsorted integer array as input and returns the “k” smallest elements in the array by using a 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

This is an array, size of the array, and a number k.

Output

It returns an integer vector that contains the first k smallest elements from the given array.

Sample input

array = {9,4,7,1,-2,6,5}   k = 3

Sample output

{-2,1,4}

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.