# 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 **K ^{th}** 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++

*chevron_right*

*filter_none*

## Java

*chevron_right*

*filter_none*

## Python3

*chevron_right*

*filter_none*

## C#

*chevron_right*

*filter_none*

**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.

## Recommended Posts:

- Find duplicates in constant array with elements 0 to N-1 in O(1) space
- Program to print an array in Pendulum Arrangement with constant space
- Print modified array after multiple array range increment operations
- K'th Smallest/Largest Element in Unsorted Array | Set 1
- Smallest element greater than X not present in the array
- Smallest element in an array that is repeated exactly 'k' times.
- Find the Kth smallest element in the sorted generated array
- K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
- K'th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time)
- Find the maximum possible value of the minimum value of modified array
- Find the modified array after performing k operations of given type
- Find an element in array such that sum of left array is equal to sum of right array
- Minimize the difference between the maximum and minimum values of the modified array
- Print modified array after executing the commands of addition and subtraction
- Constant time range add operation on an array

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.