Given an integer array, find k'th smallest element in the array where k is a positive integer less than or equal to the length of array.

For example,

Input:
 
arr = [7, 4, 6, 3, 9, 1]
k = 3
 
Output:
 
k’th smallest array element is 4

Practice this problem

A simple solution would be to use an efficient sorting algorithm to sort the array in ascending order and return the element at (k-1)'th index. The worst-case time complexity of this approach will be O(n.log(n)), where n is the size of the input. We can improve the time complexity using the following methods:

Using Max Heap

We can easily solve this problem in O(n.log(k)) time by using a max-heap, where n is the size of the input. The idea is to simply construct a max-heap of size k and insert the first k elements of array [0…k-1] into the max-heap. Then for each of the remaining array elements [k…n-1], if that element is less than the heap’s root, replace the root with the current element. Repeat this process till the array is exhausted. Now, we will be left with k smallest array elements in the max-heap, and k'th smallest element will reside at the root of the max-heap.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

k’th smallest array element is 4

Java


Download  Run Code

Output:

k’th smallest array element is 4

Python


Download  Run Code

Output:

k’th smallest element in the list is 4

Using Min Heap

We can easily solve this problem in O(n + k.log(n)) by using a min-heap. The idea is to construct a min-heap of size n and insert all the array elements input[0…n-1] into it. Then pop first k-1 elements from it. Now k'th smallest element will reside at the root of the min-heap.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

k’th smallest array element is 4

Java


Download  Run Code

Output:

k’th smallest array element is 4

Python


Download  Run Code

Output:

k’th smallest element in the list is 4

Using STL

We can easily solve this problem by using std::nth_element in C++. Following is the prototype of std::nth_element, which rearranges the elements in range [first, last) so that the element at the n'th position is the element that would be in that position in a sorted sequence:

void nth_element (RandomAccessIterator first, RandomAccessIterator n, RandomAccessIterator last)

std::nth_element is typically implemented using a fancy version of quickselect called introselect. We can imagine quickselect as a Quicksort version where the recursive call is only executed on the side, which contains the element. Introselect ensures the worst-case linear running time if quickselect takes too long (bad pivot selection). It basically switches to an algorithm with worst-case O(n) time, which is slower in most cases but saves the day when quickselect has trouble.

C++


Download  Run Code

Output:

k’th smallest array element is 7