K’th Smallest/Largest Element in Unsorted Array | Expected Linear Time
Last Updated :
24 Mar, 2025
Given an array of distinct integers and an integer k
, where k
is smaller than the array's size, the task is to find the k'th smallest element in the array.
Examples:
Input: arr = [7, 10, 4, 3, 20, 15]
, k = 3
Output: 7
Explanation: The sorted array is [3, 4, 7, 10, 15, 20]
, so the 3rd smallest element is 7
.
Input: arr = [7, 10, 4, 3, 20, 15]
, k = 4
Output: 10
Explanation: The sorted array is [3, 4, 7, 10, 15, 20]
, so the 4th smallest element is 10
.
Please note that there are multiple ways to solve this problem discussed in kth-Smallest/Largest Element in Unsorted Array. The solution discussed here works best in practice.
The idea is to use a randomized pivot selection to partition the array, reducing the search space by focusing on the subarray where the k'th element must lie.
Step by step approach:
Choose a Random Pivot: Randomly select an element as the pivot. This helps avoid the worst-case scenario in some cases (like when the array is already sorted).
Partitioning: Rearrange the array such that all elements less than the pivot are on the left side, and those greater than the pivot are on the right side.
Recursive Search: Once the pivot is positioned, if its index equals n-k
comparison , then it’s the Kth largest element. If not, recursively search the appropriate partition (left or right) based on the with n-k
.
C++
// C++ program to find K’th Smallest/
// Largest Element in Unsorted Array
#include<bits/stdc++.h>
using namespace std;
// Partition function: Rearranges elements
// around a pivot (last element)
int partition(vector<int> &arr, int l, int r) {
int x = arr[r];
int i = l;
// Iterate through the subarray
for (int j = l; j <= r - 1; j++) {
// Move elements <= pivot to the
// left partition
if (arr[j] <= x) {
swap(arr[i], arr[j]);
i++;
}
}
// Place the pivot in its correct position
swap(arr[i], arr[r]);
return i;
}
// Randomizes the pivot to avoid worst-case performance
int randomPartition(vector<int> &arr, int l, int r) {
int n = r - l + 1;
int pivot = rand() % n;
swap(arr[l + pivot], arr[r]);
return partition(arr, l, r);
}
// function to find the k'th smallest element
// using QuickSelect
int quickSelect(vector<int> &arr, int l, int r, int k) {
// Check if k is within the valid range
// of the current subarray
if (k > 0 && k <= r - l + 1) {
// Partition the array and get the
// pivot's final position
int pos = randomPartition(arr, l, r);
// If pivot is the k'th element, return it
if (pos - l == k - 1)
return arr[pos];
// If pivot's position is larger than k,
// search left subarray
if (pos - l > k - 1)
return quickSelect(arr, l, pos - 1, k);
// Otherwise, search right subarray and adjust k
// (k is reduced by the size of the left partition)
return quickSelect(arr, pos + 1, r, k - (pos - l + 1));
}
// Return infinity for invalid k (error handling)
return INT_MAX;
}
int kthSmallest(vector<int> &arr, int k) {
int n = arr.size();
return quickSelect(arr, 0, n-1, k);
}
int main() {
vector<int> arr = {12, 3, 5, 7, 4, 19, 26};
int k = 3;
cout << kthSmallest(arr, k);
return 0;
}
Java
// Java program to find K’th Smallest/
// Largest Element in Unsorted Array
import java.util.Random;
class GfG {
// Partition function: Rearranges elements
// around a pivot (last element)
static int partition(int[] arr, int l, int r) {
int x = arr[r];
int i = l;
// Iterate through the subarray
for (int j = l; j <= r - 1; j++) {
// Move elements <= pivot to the left partition
if (arr[j] <= x) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
}
}
// Place the pivot in its correct position
int temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
return i;
}
// Randomizes the pivot to avoid worst-case performance
static int randomPartition(int[] arr, int l, int r) {
Random rand = new Random();
int n = r - l + 1;
int pivot = rand.nextInt(n);
int temp = arr[l + pivot];
arr[l + pivot] = arr[r];
arr[r] = temp;
return partition(arr, l, r);
}
// function to find the k'th smallest element using QuickSelect
static int quickSelect(int[] arr, int l, int r, int k) {
// Check if k is within the valid range of
// the current subarray
if (k > 0 && k <= r - l + 1) {
// Partition the array and get the
// pivot's final position
int pos = randomPartition(arr, l, r);
// If pivot is the k'th element, return it
if (pos - l == k - 1)
return arr[pos];
// If pivot's position is larger than k,
// search left subarray
if (pos - l > k - 1)
return quickSelect(arr, l, pos - 1, k);
// Otherwise, search right subarray and adjust k
// (k is reduced by the size of the left partition)
return quickSelect(arr, pos + 1, r, k - (pos - l + 1));
}
// Return infinity for invalid k (error handling)
return Integer.MAX_VALUE;
}
static int kthSmallest(int[] arr, int k) {
int n = arr.length;
return quickSelect(arr, 0, n - 1, k);
}
public static void main(String[] args) {
int[] arr = {12, 3, 5, 7, 4, 19, 26};
int k = 3;
System.out.println(kthSmallest(arr, k));
}
}
Python
# Python program to find K’th Smallest/
# Largest Element in Unsorted Array
import random
# Partition function: Rearranges elements
# around a pivot (last element)
def partition(arr, l, r):
x = arr[r]
i = l
# Iterate through the subarray
for j in range(l, r):
# Move elements <= pivot to the left partition
if arr[j] <= x:
arr[i], arr[j] = arr[j], arr[i]
i += 1
# Place the pivot in its correct position
arr[i], arr[r] = arr[r], arr[i]
return i
# Randomizes the pivot to avoid worst-case performance
def randomPartition(arr, l, r):
n = r - l + 1
pivot = random.randint(0, n - 1)
arr[l + pivot], arr[r] = arr[r], arr[l + pivot]
return partition(arr, l, r)
# function to find the k'th smallest element using QuickSelect
def quickSelect(arr, l, r, k):
# Check if k is within the valid range of the current subarray
if 0 < k <= r - l + 1:
# Partition the array and get the pivot's final position
pos = randomPartition(arr, l, r)
# If pivot is the k'th element, return it
if pos - l == k - 1:
return arr[pos]
# If pivot's position is larger than k, search left subarray
if pos - l > k - 1:
return quickSelect(arr, l, pos - 1, k)
# Otherwise, search right subarray and adjust k
# (k is reduced by the size of the left partition)
return quickSelect(arr, pos + 1, r, k - (pos - l + 1))
# Return infinity for invalid k (error handling)
return float('inf')
def kthSmallest(arr, k):
n = len(arr)
return quickSelect(arr, 0, n - 1, k)
if __name__ == "__main__":
arr = [12, 3, 5, 7, 4, 19, 26]
k = 3
print(kthSmallest(arr, k))
C#
// C# program to find K’th Smallest/
// Largest Element in Unsorted Array
using System;
class GfG {
// Partition function: Rearranges elements
// around a pivot (last element)
static int partition(int[] arr, int l, int r) {
int x = arr[r];
int i = l;
// Iterate through the subarray
for (int j = l; j <= r - 1; j++) {
// Move elements <= pivot to the left partition
if (arr[j] <= x) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
}
}
// Place the pivot in its correct position
int temp2 = arr[i];
arr[i] = arr[r];
arr[r] = temp2;
return i;
}
// Randomizes the pivot to avoid worst-case performance
static int randomPartition(int[] arr, int l, int r) {
Random rand = new Random();
int n = r - l + 1;
int pivot = rand.Next(n);
int temp = arr[l + pivot];
arr[l + pivot] = arr[r];
arr[r] = temp;
return partition(arr, l, r);
}
// function to find the k'th smallest element using QuickSelect
static int quickSelect(int[] arr, int l, int r, int k) {
// Check if k is within the valid range of the
// current subarray
if (k > 0 && k <= r - l + 1) {
// Partition the array and get the pivot's
// final position
int pos = randomPartition(arr, l, r);
// If pivot is the k'th element, return it
if (pos - l == k - 1)
return arr[pos];
// If pivot's position is larger than k, search
// left subarray
if (pos - l > k - 1)
return quickSelect(arr, l, pos - 1, k);
// Otherwise, search right subarray and adjust k
// (k is reduced by the size of the left partition)
return quickSelect(arr, pos + 1, r, k - (pos - l + 1));
}
// Return infinity for invalid k (error handling)
return int.MaxValue;
}
static int kthSmallest(int[] arr, int k) {
int n = arr.Length;
return quickSelect(arr, 0, n - 1, k);
}
static void Main() {
int[] arr = {12, 3, 5, 7, 4, 19, 26};
int k = 3;
Console.WriteLine(kthSmallest(arr, k));
}
}
JavaScript
// JavaScript program to find K’th Smallest/
// Largest Element in Unsorted Array
// Partition function: Rearranges elements
// around a pivot (last element)
function partition(arr, l, r) {
let x = arr[r];
let i = l;
// Iterate through the subarray
for (let j = l; j <= r - 1; j++) {
// Move elements <= pivot to the left partition
if (arr[j] <= x) {
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
}
}
// Place the pivot in its correct position
[arr[i], arr[r]] = [arr[r], arr[i]];
return i;
}
// Randomizes the pivot to avoid worst-case performance
function randomPartition(arr, l, r) {
let n = r - l + 1;
let pivot = Math.floor(Math.random() * n);
[arr[l + pivot], arr[r]] = [arr[r], arr[l + pivot]];
return partition(arr, l, r);
}
// function to find the k'th smallest element using QuickSelect
function quickSelect(arr, l, r, k) {
// Check if k is within the valid range of the current subarray
if (k > 0 && k <= r - l + 1) {
// Partition the array and get the pivot's final position
let pos = randomPartition(arr, l, r);
// If pivot is the k'th element, return it
if (pos - l == k - 1)
return arr[pos];
// If pivot's position is larger than k, search left subarray
if (pos - l > k - 1)
return quickSelect(arr, l, pos - 1, k);
// Otherwise, search right subarray and adjust k
// (k is reduced by the size of the left partition)
return quickSelect(arr, pos + 1, r, k - (pos - l + 1));
}
// Return Infinity for invalid k (error handling)
return Infinity;
}
function kthSmallest(arr, k) {
let n = arr.length;
return quickSelect(arr, 0, n - 1, k);
}
let arr = [12, 3, 5, 7, 4, 19, 26];
let k = 3;
console.log(kthSmallest(arr, k));
Time Complexity: O(n) The worst-case time complexity of the above solution is still O(n2). In the worst case, the randomized function may always pick a corner element. However, the average-case time complexity is O(n)
. The assumption in the analysis is, random number generator is equally likely to generate any number in the input range.
Auxiliary Space: O(1) since using constant variables.
Even if the worst case time complexity is quadratic, this solution works best in practice.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read