# Kth smallest element in array

Given an array of integers which is non sorted,** find k^{th} smallest element in that array**. For example: if input array is A = [3,5,1,2,6,9,7], 4

^{th}smallest element in array A is 5, because if you sort the array A, it looks like A = [1,2,3,5,6,7,9] and now you can easily see that 4

^{th}element is 5.

This problem is commonly asked in Microsoft and Amazon interviews as it has multiple layers and there is some many things that can be measured with this one problem.

## Kth smallest element : Line of thought

First of all, in any interview, try to come up with brute force solution. Brute force solution to find K^{th} smallest element in array of integers would be to sort array and return `A[k-1]` element (K-1 as array is zero base indexed).

What is the complexity of brute force solution? It’s `O(n`

? Well, we have sort algorithms like merge sort and heap sort which work in ^{2})`O(n log n)`

complexity. Problem with both searches is that they use additional space. Quick sort is another sort algorithm. It has problem that it’s worst case complexity will be `O(n`

, which happens when input is completely sorted.^{2})

In our case, input is given as unsorted already, so we can expect that quick sort will function with `O(n log n)`

complexity which is it’s average case complexity. Advantage of using quick sort is that there is no additional space complexity.

### Optimising quick sort

Let’s see how quick sort works and see if we can optimize solution further?

Idea behind quick sort is to find correct place for the selected pivot. Once pivot is at correct position, all the elements on left side of pivot are smaller and on right side of pivot are greater than pivot. This step is partitioning.

If after partitioning, pivot is at position j, can we say that pivot is actually j^{th} smallest element of the array? What if `j` is equal to `k`? Well problem solved, we found the k^{th} smallest element.

If `j` is less than `k`, left subarray is less than `k`, we need to include more elements from right subarray, therefore k^{th} smallest element is in right subarray somewhere. We have already found `j` smallest elements, all we need to find is `k-j` elements from right subarray.

What if `j` is greater than `k`? In this case, we have to drop some elements from left subarray, so our search space would be left subarray after partition.

Theoretically, this algorithm still has complexity of `O(n log n)`

, but practically, you do not need to sort the entire array before you find k smallest elements.

#### Algorithm to find K smallest elements in array

- Select a pivot and partition the array with pivot at correct position
`j` - If position of pivot,
`j`, is equal to`k`, return A[j]. - If
`j`is less than`k`, discard array from`start`to`j`, and look for (k-j)^{th}smallest element in right sub array, go to step 1. - If
`j`is greater than`k`, discard array from`j`to`end`and look for k^{th}element in left subarray, go to step 1

Let’s take an example and see if this algorithm works? A = [4, 2, 1, 7, 5, 3, 8, 10, 9, 6 ], and we have to find fifth smallest element in array A.

Start with pivot as first index of array, so `pivot` = 0, partition the array into two parts around pivot such that all elements on left side of pivot element, i.e. `A[pivot]`

are smaller and all elements on right side are greater than `A[pivot]`

.

Start with pivot as first index of array, so `pivot` = 0, partition the array into two parts around pivot such that all elements on left side of pivot element, i.e. `A[pivot]`

are smaller and all elements on right side are greater than `A[pivot]`

.

In our example, array A will look like below after pivot has found it’s correct position.

If `pivot` == `k-1` (array is represented as zero base index), then `A[pivot]`

is k^{th} smallest element. Since `pivot` (3) is less than `k-1` (4), look for k^{th} smallest element on right side of the `pivot`.

k remains as it is as opposed to k-j mentioned in algorithm as pivot is given w.r.t entire array and not w.r.t subarray.

In second iteration, `pivot` = 4 (index and not element). After second execution of quick sort array A will be like

`pivot`(4) which is equal to `k-1`(5-1). 5th smallest element in array A is 5.

### Implementation

package com.company; /** * Created by sangar on 30.9.18. */ public class KthSmallest { private void swap(int[] a, int i, int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp; } private int partition(int[] a, int start, int end){ int pivot = a[start]; int i = start+1; int j = end; while(i < j){ while(a[i] < pivot) i++; while(a[j] > pivot) j--; if(i < j) { swap(a, i, j); } } swap(a, start, j); return j; } public int findKthSmallestElement(int a[], int start, int end, int k){ if(start < end){ int p = partition(a, start, end); if(p == k-1){ return a[p]; } if(p > k-1) return findKthSmallestElement(a, start, p, k); if(p < k-1) return findKthSmallestElement(a, p+1, end, k); } return -1; } }

package test; import com.company.KthSmallest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Created by sangar on 28.8.18. */ public class KthSmallestTest { KthSmallest tester = new KthSmallest(); private int[] a = {4, 2, 1, 7, 5, 3, 8, 10, 9}; @Test public void kthSmallest() { assertEquals(7, tester.findKthSmallestElement(a,0,8,6)); } @Test public void firstSmallest() { assertEquals(1, tester.findKthSmallestElement(a,0,8,1)); } @Test public void lastSmallest() { assertEquals(10, tester.findKthSmallestElement(a,0,8,9)); } @Test public void kGreaterThanSize() { assertEquals(-1, tester.findKthSmallestElement(a,0,8,15)); } @Test public void emptyArray() { int[] a = {}; assertEquals(-1, tester.findKthSmallestElement(a,0,0,1)); } @Test public void nullArray() { assertEquals(-1, tester.findKthSmallestElement(null,0,0,1)); } }

Complexity of using quick sort algorithm to find kth smallest element in array of integers in still O(n log n).

## K^{th} smallest element using heaps

Imagine a case where there are a billion integers in array and you have to find 5 smallest elements from that array. Complexity of O(n log n) is too costly for that use case. Above algorithm using quick sort does not take into consideration disparity between k and n.

We want top `k` elements, how about we chose those `k` elements randomly, call it `set A`

and then go through all other `n-k` elements, call it `set B`

, check if element from set B (n-k elements) can displace element in set A (k elements)?

What will be condition for an element from set B to replace an element in set A? Well, if the new element is less than maximum in set A, than maximum in set A cannot be in set of k smallest elements right? Maximum element in set A would be replaced by the new element from set B.

Now, problem is how to quickly find maximum out of set A. Heap is the best data structure there. What kind of heap: min heap or max heap? Max heap as it store the maximum of set at the root of it.

Let’s defined concrete steps to find k smallest elements using max heap.

- Create a max heap of size k from first k elements of array.
- Scan all elements in array one by one.
- If current element is less than max on heap, add current element to heap and heapify.
- If not, then go to next element.

- At the end, max heap will contain k smallest elements of array and root will be kth smallest element.

Let’s take an example and see if this algorithm works? Input array is shown below and we have to find 6th smallest element in this array.

Step 1 : Create a max heap with first 6 elements of array.

Step 2 : Take next element from set B and check if it is less than root of max heap. In this case, yes it is. Remove the root and insert the new element into max heap.

Step 2 : It continues to 10, nothing happens as new element is greater than root of max heap. Same for 9. At 6, again root of max heap is greater than 6. So remove the root and add 6 to max heap.

Array scan is finished, so just return root of max heap, 6 which is sixth smallest element in given array.

public int findKthSmallestElementUsingHeap(int a[], int k){ //https://stackoverflow.com/questions/11003155/change-priorityqueue-to-max-priorityqueue PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, Collections.reverseOrder()); if(a == null || k > a.length) return -1; //Create max with first k elements for(int i=0; i<k; i++){ maxHeap.add(a[i]); } /*Keep updating max heap based on new element If new element is less than root, remove root and add new element */ for(int i=k; i<a.length; i++){ if(maxHeap.peek() > a[i]){ maxHeap.remove(); maxHeap.add(a[i]); } } return maxHeap.peek(); }

Can you calculate the complexity of above algorithm? `heapify()`

has complexity of `log(k)`

with `k` elements on heap. In worst case, we have to do `heapify()`

for all elements in array, which is n, so overall complexity of algorithm becomes `O(n log k)`

. Also, there is additional space complexity of `O(k)`

to store heap.

When is very small as compared to `n`, this algorithm again depends on the size of array.

We want k smallest elements, if we pick first `k` elements from a min heap, will it solve the problem? I think so. Create a min heap of `n` elements in place from the given array, and then pick first `k` elements.

Creation of heap has complexity of `O(n)`

, do more reading on it. All we need to do is delete `k` times from this heap, each time there will be `heapify()`

. It will have complexity of `O(log n)`

for `n` element heap. So, overall complexity would be `O(n + k log n)`

.

*Depending on what you want to optimize, select correct method to find kth smallest element in array.*

Please share if there is something wrong or missing. If you are interested in taking coaching sessions from our experienced teachers, please reach out to us at communications@algorithmsandme.com