Find the Kth Maximum and Minimum Element of an Array: Sorting, Heap and Quickselect
Find the Kth smallest and Kth largest element of an array. Compare sorting, heaps and Quickselect, see an animated dry run, and get tested code in Java, C, C++, JavaScript and Python.
"Find the Kth smallest element" is one of the most asked array questions in interviews. It is a great problem because there are three good answers, each better than the last: sorting, a heap, and Quickselect. In this post you will learn how to think about the problem, compare the approaches, watch Quickselect animated, and get tested solutions in Java, C, C++, JavaScript and Python.
Problem statement#
Given an array arr of n integers and a number k (1 <= k <= n), find the Kth smallest and the Kth largest element.
Input: arr = [7, 10, 4, 3, 20, 15], k = 3
Output: 3rd smallest = 7, 3rd largest = 10
Explanation: sorted array is [3, 4, 7, 10, 15, 20]
3rd from the left is 7, 3rd from the right is 10How to think about this problem#
The key observation: the Kth smallest element is the value that would sit at index k - 1 if the array were sorted. The Kth largest sits at index n - k. So both questions are really the same question: "which value belongs at position p in sorted order?"
Now ask: do we really need the whole array sorted to answer that? No. We only need to know that everything to the left of position p is smaller and everything to the right is bigger. That idea is exactly what the partition step of Quicksort gives us, and it leads to Quickselect.
Convert "Kth largest" into "Kth smallest" with target = n - k. Then you only need one function for both.
Approaches#
Approach 1: Sort the array#
Sort, then read arr[k - 1] and arr[n - k]. Simple and correct, but it does more work than needed: O(n log n).
Approach 2: Use a heap of size k#
For the Kth smallest, keep a max-heap of the k smallest values seen so far. For each new value, push it, and if the heap grows beyond k, pop the largest. At the end, the top of the heap is the answer. For the Kth largest, use a min-heap instead. This costs O(n log k), which is great when k is small or when data arrives as a stream.
Approach 3: Quickselect (best on average)#
- Pick a pivot (a random element works best).
- Partition: move every value smaller than the pivot to its left. The pivot lands at its final sorted index
p. - If
p == target, you are done:arr[p]is the answer. - If
p < target, the answer is on the right. Repeat only on the right part. - If
p > target, repeat only on the left part.
Unlike Quicksort, we throw away one side every time, so the average work is n + n/2 + n/4 + ..., which is about 2n, giving O(n) on average.
| Approach | Time | Extra space | Best for |
|---|---|---|---|
| Sorting | O(n log n) | O(1) to O(n) | Quick, simple code |
| Heap of size k | O(n log k) | O(k) | Small k, streaming data |
| Quickselect | O(n) average, O(n²) worst | O(1) | Fastest in practice |
Dry run (animated)#
Quickselect finding the 3rd smallest (target index 2) in [7, 10, 4, 3, 20, 15]. To keep the animation easy to follow it always uses the last element as the pivot; the code below uses a random pivot. Orange is the pivot, green is the pivot after it lands in its sorted position.
- Pivot 15. Smaller values 7, 10, 4, 3 move left, giving
[7, 10, 4, 3, 15, 20]. 15 lands at index 4. Target 2 is to the left, so drop the right side. - Search
[7, 10, 4, 3]with pivot 3. Nothing is smaller, so 3 lands at index 0:[3, 10, 4, 7, 15, 20]. Target 2 is to the right. - Search
[10, 4, 7]with pivot 7. Only 4 is smaller, giving[3, 4, 7, 10, 15, 20]. 7 lands at index 2, which is the target. Answer: 7.
Running the same search with target n - k = 3 gives the 3rd largest, 10.
Code#
Every version works on a copy, so the original array is not changed.
Java#
import java.util.Random;
public class Main {
static Random rand = new Random();
// Places a random pivot at its sorted position and returns that position
static int partition(int[] arr, int low, int high) {
int r = low + rand.nextInt(high - low + 1);
int t = arr[r]; arr[r] = arr[high]; arr[high] = t;
int pivot = arr[high], i = low;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
t = arr[i]; arr[i] = arr[j]; arr[j] = t;
i++;
}
}
t = arr[i]; arr[i] = arr[high]; arr[high] = t;
return i;
}
// Returns the element that would sit at index `target` if arr were sorted
static int quickSelect(int[] arr, int target) {
int low = 0, high = arr.length - 1;
while (true) {
int p = partition(arr, low, high);
if (p == target) return arr[p];
if (p < target) low = p + 1;
else high = p - 1;
}
}
static int kthSmallest(int[] arr, int k) {
return quickSelect(arr.clone(), k - 1);
}
static int kthLargest(int[] arr, int k) {
return quickSelect(arr.clone(), arr.length - k);
}
public static void main(String[] args) {
int[] arr = {7, 10, 4, 3, 20, 15};
int k = 3;
System.out.println(k + "rd smallest: " + kthSmallest(arr, k)); // 7
System.out.println(k + "rd largest: " + kthLargest(arr, k)); // 10
}
}C#
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
static void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
/* Places a random pivot at its sorted position and returns that position */
static int partition(int arr[], int low, int high) {
int r = low + rand() % (high - low + 1);
swap(&arr[r], &arr[high]);
int pivot = arr[high], i = low;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
swap(&arr[i], &arr[j]);
i++;
}
}
swap(&arr[i], &arr[high]);
return i;
}
/* Returns the element that would sit at index `target` if arr were sorted */
static int quickSelect(int arr[], int n, int target) {
int low = 0, high = n - 1;
while (1) {
int p = partition(arr, low, high);
if (p == target) return arr[p];
if (p < target) low = p + 1;
else high = p - 1;
}
}
int kthSmallest(const int arr[], int n, int k) {
int *copy = malloc(n * sizeof(int));
memcpy(copy, arr, n * sizeof(int));
int ans = quickSelect(copy, n, k - 1);
free(copy);
return ans;
}
int kthLargest(const int arr[], int n, int k) {
return kthSmallest(arr, n, n - k + 1);
}
int main(void) {
srand((unsigned)time(NULL));
int arr[] = {7, 10, 4, 3, 20, 15};
int n = sizeof(arr) / sizeof(arr[0]), k = 3;
printf("%drd smallest: %d\n", k, kthSmallest(arr, n, k)); /* 7 */
printf("%drd largest: %d\n", k, kthLargest(arr, n, k)); /* 10 */
return 0;
}C++#
#include <iostream>
#include <vector>
#include <random>
using namespace std;
mt19937 rng(random_device{}());
// Places a random pivot at its sorted position and returns that position
int partition(vector<int>& arr, int low, int high) {
int r = uniform_int_distribution<int>(low, high)(rng);
swap(arr[r], arr[high]);
int pivot = arr[high], i = low;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) swap(arr[i++], arr[j]);
}
swap(arr[i], arr[high]);
return i;
}
// Returns the element that would sit at index `target` if arr were sorted
int quickSelect(vector<int> arr, int target) { // copy, original stays unchanged
int low = 0, high = (int)arr.size() - 1;
while (true) {
int p = partition(arr, low, high);
if (p == target) return arr[p];
if (p < target) low = p + 1;
else high = p - 1;
}
}
int kthSmallest(const vector<int>& arr, int k) { return quickSelect(arr, k - 1); }
int kthLargest(const vector<int>& arr, int k) { return quickSelect(arr, (int)arr.size() - k); }
int main() {
vector<int> arr = {7, 10, 4, 3, 20, 15};
int k = 3;
cout << k << "rd smallest: " << kthSmallest(arr, k) << endl; // 7
cout << k << "rd largest: " << kthLargest(arr, k) << endl; // 10
return 0;
}JavaScript#
// Places a random pivot at its sorted position and returns that position
function partition(arr, low, high) {
const r = low + Math.floor(Math.random() * (high - low + 1));
[arr[r], arr[high]] = [arr[high], arr[r]];
const pivot = arr[high];
let i = low;
for (let j = low; j < high; j++) {
if (arr[j] < pivot) {
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
}
}
[arr[i], arr[high]] = [arr[high], arr[i]];
return i;
}
// Returns the element that would sit at index `target` if arr were sorted
function quickSelect(arr, target) {
let low = 0;
let high = arr.length - 1;
while (true) {
const p = partition(arr, low, high);
if (p === target) return arr[p];
if (p < target) low = p + 1;
else high = p - 1;
}
}
const kthSmallest = (arr, k) => quickSelect([...arr], k - 1);
const kthLargest = (arr, k) => quickSelect([...arr], arr.length - k);
const arr = [7, 10, 4, 3, 20, 15];
const k = 3;
console.log(`${k}rd smallest: ${kthSmallest(arr, k)}`); // 7
console.log(`${k}rd largest: ${kthLargest(arr, k)}`); // 10Python#
import random
def partition(arr, low, high):
"""Places a random pivot at its sorted position and returns that position."""
r = random.randint(low, high)
arr[r], arr[high] = arr[high], arr[r]
pivot, i = arr[high], low
for j in range(low, high):
if arr[j] < pivot:
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[high] = arr[high], arr[i]
return i
def quick_select(arr, target):
"""Returns the element that would sit at index `target` if arr were sorted."""
low, high = 0, len(arr) - 1
while True:
p = partition(arr, low, high)
if p == target:
return arr[p]
if p < target:
low = p + 1
else:
high = p - 1
def kth_smallest(arr, k):
return quick_select(arr[:], k - 1)
def kth_largest(arr, k):
return quick_select(arr[:], len(arr) - k)
arr = [7, 10, 4, 3, 20, 15]
k = 3
print(f"{k}rd smallest: {kth_smallest(arr, k)}") # 7
print(f"{k}rd largest: {kth_largest(arr, k)}") # 10Complexity analysis#
- Time: O(n) on average. Each partition removes about half of the remaining elements. With a random pivot, the
O(n²)worst case (always picking the smallest or largest value) is extremely unlikely. - Space: O(1) extra for the iterative loop, plus
O(n)for the copy if you want to keep the original array unchanged.
Edge cases and common mistakes#
- Off-by-one: k is 1-based but array indexes are 0-based. Kth smallest is index
k - 1, Kth largest is indexn - k. - Duplicates: handled correctly. For
[5, 5, 1]and k = 2, the answer is 5. - Fixed pivot on sorted input: always choosing the last element makes Quickselect
O(n²)on already sorted arrays. Always randomise the pivot in real code. - Invalid k: check
1 <= k <= nbefore searching.
C++ has this built in: std::nth_element runs Quickselect-style partitioning for you. In Python, heapq.nsmallest(k, arr)[-1] gives the Kth smallest using a heap.
Key takeaways#
- Kth smallest is the value at index
k - 1in sorted order; Kth largest is at indexn - k. - Sorting solves it in
O(n log n); a heap of size k brings it down toO(n log k). - Quickselect partitions around a pivot and keeps only the side that holds the target, giving
O(n)on average. - Always use a random pivot to avoid the
O(n²)worst case on sorted input.