Kth smallest element in the array using constant space when array can’t be modified

Given an array arr[] of size N and an integer K, the task is to find the Kth smallest element from the array in constant extra space and the array can’t be modified.

Examples:

Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3
Output: 7
Given array in sorted is {3, 4, 7, 10, 15, 20}
where 7 is the third smallest element.

Input: arr[] = {12, 3, 5, 7, 19}, K = 2
Output: 5

Approach: First we find the min and max element from the array. Then we set low = min, high = max and mid = (low + high) / 2.
Now, perform a modified binary search, and for each mid we count the number of elements less than mid and equal to mid. If countLess < k and countLess + countEqual ≥ k then mid is our answer, else we have to modify our low and high.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


Output:

7

Time Complexity: O(N log(Max – Min)) where Max and Min are the maximum and minimum elements from the array respectively and N is the size of the array.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.