New update is available. Click here to update.

Last Updated: 21 Nov, 2020

Difficulty: Easy

```
The first line of input contains an integer 'T' representing the number of the test case. Then the test case follows.
The first line of each test case contains two space-separated integers ‘N’ representing the size of the array and ‘K’.
The second line contains N space-separated integers that represent elements of the array ARR.
```

```
For each test case, print a single line that contains a single integer which is the Kth smallest element of the array.
The output of each test case will be printed in a separate line.
```

```
You do not need to print anything; it has already been taken care of. Just implement the given function.
```

```
1 <= T <= 100
1 <= N <=10 ^ 4
1 <= K <= N
1 <= ARR[i] <= 10 ^ 9
Time limit: 1 sec.
```

- We’ll use min heaps to store the elements of 'ARR' and perform 'K' GETMIN operations to get Kth minimum element.
- We’ll create an empty heap MINHEAP.
- We’ll add 'ARR'['I'] to MINHEAP for each 0 <= 'I' < 'N'. Every time the element is added the structure will HEAPIFY itself, such that the minimum element is always at the root node of the heap.
- Call GETMIN function 'K' times and store the result in 'KTHMIN' variable.
- Return 'KTHMIN'.

We’ll use a max heap of fixed size 'K' to store the elements of 'ARR' and perform a single 'GETMAX' operation to get 'K'th minimum element.

- We’ll create an empty heap 'MAXHEAP'.
- We’ll add 'ARR'['I'] to 'MAXHEAP' for each 0 <= 'I' < 'K'. Every time the element is added the structure will HEAPIFY itself, such that the maximum element is always at the root node of the heap.
- For each 'I' where, 'K' <= 'I' <= N, If 'ARR'['I'] < 'MAXHEAP'.'GETMAX'
- Replace ROOT of 'MAXHEAP' by 'ARR'['I'] .
- HEAPIFY the 'MAXHEAP'.

- Call 'GETMAX' and store its value in 'KTHMIN'.
- Return 'KTHMIN'.

SIMILAR PROBLEMS

Longest Subarray With Zero Sum

Posted: 3 Nov, 2022

Difficulty: Moderate

Merge Two Sorted Arrays Without Extra Space

Posted: 19 Nov, 2022

Difficulty: Moderate

Ninja And The Strictly Increasing Array

Posted: 27 Nov, 2022

Difficulty: Moderate

Negative To The End

Posted: 16 Dec, 2022

Difficulty: Easy

Sort 0s, 1s, 2s

Posted: 24 Dec, 2022

Difficulty: Easy

Popular Interview Problems: