K’th Smallest Element in Unsorted Array
Last Updated :
30 Aug, 2025
Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array.
Examples:
Input: arr[] = [7, 10, 4, 3, 20, 15], K = 3
Output: 7
Input: arr[] = [7, 10, 4, 3, 20, 15], K = 4
Output: 10
[Naive Approach] Using Sorting - O(n log(n)) Time and O(1) Space
The very basic approach is to sort the given array and return the element at the index K - 1.
Below is the Implementation of the above approach:
C++
// C++ program to find K'th smallest element
#include <bits/stdc++.h>
using namespace std;
// Function to return K'th smallest element in a given vector
int kthSmallest(vector<int>& arr, int K)
{
// Sort the given vector
sort(arr.begin(), arr.end());
// Return k'th element in the sorted vector
return arr[K - 1];
}
// Driver's code
int main()
{
vector<int> arr = {12, 3, 5, 7, 19};
int K = 2;
// Function call
cout << kthSmallest(arr, K);
return 0;
}
C
// C program to find K'th smallest element
#include <stdio.h>
#include <stdlib.h>
// Compare function for qsort
int cmpfunc(const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}
// Function to return K'th smallest
// element in a given array
int kthSmallest(int arr[], int N, int K)
{
// Sort the given array
qsort(arr, N, sizeof(int), cmpfunc);
// Return k'th element in the sorted array
return arr[K - 1];
}
// Driver's code
int main()
{
int arr[] = {12, 3, 5, 7, 19};
int N = sizeof(arr) / sizeof(arr[0]), K = 2;
// Function call
printf(" %d", kthSmallest(arr, N, K));
return 0;
}
Java
// Java code for Kth smallest element
// in an array
import java.util.Arrays;
import java.util.Collections;
class GFG {
// Function to return K'th smallest
// element in a given array
public static int kthSmallest(Integer[] arr, int K)
{
// Sort the given array
Arrays.sort(arr);
// Return K'th element in
// the sorted array
return arr[K - 1];
}
// driver's code
public static void main(String[] args)
{
Integer arr[] = new Integer[] { 12, 3, 5, 7, 19 };
int K = 2;
// Function call
System.out.print(kthSmallest(arr, K));
}
}
Python
# Python3 program to find K'th smallest
# element
# Function to return K'th smallest
# element in a given array
def kthSmallest(arr, N, K):
# Sort the given array
arr.sort()
# Return k'th element in the
# sorted array
return arr[K - 1]
# Driver code
if __name__ == '__main__':
arr = [12, 3, 5, 7, 19]
N = len(arr)
K = 2
# Function call
print(kthSmallest(arr, N, K))
C#
// C# code for Kth smallest element
// in an array
using System;
class GFG {
// Function to return K'th smallest
// element in a given array
public static int kthSmallest(int[] arr, int K)
{
// Sort the given array
Array.Sort(arr);
// Return k'th element in
// the sorted array
return arr[K - 1];
}
// driver's program
public static void Main()
{
int[] arr = new int[] { 12, 3, 5, 7, 19 };
int K = 2;
// Function call
Console.Write(kthSmallest(arr, K));
}
}
JavaScript
// Simple Javascript program to find K'th smallest element
// Function to return K'th smallest element in a given array
function kthSmallest(arr, N, K)
{
// Sort the given array
arr.sort((a,b) => a-b);
// Return k'th element in the sorted array
return arr[K - 1];
}
// Driver program to test above methods
let arr = [12, 3, 5, 7, 19];
let N = arr.length, K = 2;
console.log( kthSmallest(arr, N, K));
PHP
<?php
// Function to return K'th smallest element
function kthSmallest($arr, $K) {
sort($arr); // Sort the array
return $arr[$K - 1]; // Return K'th smallest
}
// Driver code
$arr = array(12, 3, 5, 7, 19);
$K = 2;
// Function call
echo kthSmallest($arr, $K);
?>
[Expected Approach] Using Max-Heap
The intuition behind this approach is to maintain a max heap (priority queue) of size K while iterating through the array. Doing this ensures that the max heap always contains the K smallest elements encountered so far. If the size of the max heap exceeds K, remove the largest element this step ensures that the heap maintains the K smallest elements encountered so far. In the end, the max heap's top element will be the Kth smallest element.
Code Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find the kth smallest array element
int kthSmallest(vector<int>& arr, int K)
{
// Create a max heap (priority queue)
priority_queue<int> pq;
// Iterate through the array elements
for (int i = 0; i < arr.size(); i++)
{
// Push the current element onto the max heap
pq.push(arr[i]);
// If the size of the max heap exceeds K, remove the largest element
if (pq.size() > K)
pq.pop();
}
// Return the Kth smallest element (top of the max heap)
return pq.top();
}
// Driver's code:
int main()
{
vector<int> arr = {10, 5, 4, 3, 48, 6, 2, 33, 53, 10};
int K = 4;
// Function call
cout << kthSmallest(arr, K);
}
Java
import java.util.PriorityQueue;
public class KthSmallestElement {
// Function to find the kth smallest array element
public static int kthSmallest(int[] arr, int N, int K)
{
// Create a max heap (priority queue)
PriorityQueue<Integer> pq
= new PriorityQueue<>((a, b) -> b - a);
// Iterate through the array elements
for (int i = 0; i < N; i++) {
// Push the current element onto the max heap
pq.offer(arr[i]);
// If the size of the max heap exceeds K, remove
// the largest element
if (pq.size() > K)
pq.poll();
}
// Return the Kth smallest element (top of the max
// heap)
return pq.peek();
}
// Driver's code:
public static void main(String[] args)
{
int N = 10;
int[] arr = { 10, 5, 4, 3, 48, 6, 2, 33, 53, 10 };
int K = 4;
// Function call
System.out.println(kthSmallest(arr, N, K));
}
}
Python
import heapq
# Function to find the kth smallest array element
def kthSmallest(arr, K):
# Create a max heap (priority queue)
max_heap = []
# Iterate through the array elements
for num in arr:
# Push the negative of the current element onto the max heap
heapq.heappush(max_heap, -num)
# If the size of the max heap exceeds K, remove the largest element
if len(max_heap) > K:
heapq.heappop(max_heap)
# Return the Kth smallest element (top of the max heap, negated)
return -max_heap[0]
# Driver's code:
if __name__ == "__main__":
arr = [10, 5, 4, 3, 48, 6, 2, 33, 53, 10]
K = 4
# Function call
print(kthSmallest(arr, K))
C#
using System;
using System.Collections.Generic;
class Solution
{
// Function to find the kth smallest array element
static int KthSmallest(List<int> arr, int K)
{
// Create a max heap using a custom comparer
SortedSet<(int val, int idx)> maxHeap = new SortedSet<(int val, int idx)>(
Comparer<(int val, int idx)>.Create((a, b) =>
{
int cmp = b.val.CompareTo(a.val); // sort by value descending
if (cmp == 0) return b.idx.CompareTo(a.idx); // break ties with index
return cmp;
}));
// Iterate through the array elements
for (int i = 0; i < arr.Count; i++)
{
// Push the current element onto the max heap
maxHeap.Add((arr[i], i));
// If the size of the max heap exceeds K, remove the largest element
if (maxHeap.Count > K)
maxHeap.Remove(maxHeap.Min); // remove largest element
}
// Return the Kth smallest element (top of the max heap)
return maxHeap.Min.val;
}
// Driver's code:
static void Main()
{
List<int> arr = new List<int> { 10, 5, 4, 3, 48, 6, 2, 33, 53, 10 };
int K = 4;
// Function call
Console.WriteLine(KthSmallest(arr, K));
}
}
JavaScript
// Function to find the kth smallest array element
function kthSmallest(arr, K)
{
// Create a max heap (priority queue)
let pq = new MaxHeap();
// Iterate through the array elements
for (let i = 0; i < arr.length; i++) {
// Push the current element onto the max heap
pq.push(arr[i]);
// If the size of the max heap exceeds K, remove the
// largest element
if (pq.size() > K)
pq.pop();
}
// Return the Kth smallest element (top of the max heap)
return pq.top();
}
// MaxHeap class definition
class MaxHeap {
constructor() { this.heap = []; }
push(val)
{
this.heap.push(val);
this.heapifyUp(this.heap.length - 1);
}
pop()
{
if (this.heap.length === 0) {
return null;
}
if (this.heap.length === 1) {
return this.heap.pop();
}
const root = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapifyDown(0);
return root;
}
top()
{
if (this.heap.length === 0) {
return null;
}
return this.heap[0];
}
size() { return this.heap.length; }
heapifyUp(index)
{
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if (this.heap[parentIndex]
>= this.heap[index]) {
break;
}
this.swap(parentIndex, index);
index = parentIndex;
}
}
heapifyDown(index)
{
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let largestIndex = index;
if (leftChildIndex < this.heap.length
&& this.heap[leftChildIndex]
> this.heap[largestIndex]) {
largestIndex = leftChildIndex;
}
if (rightChildIndex < this.heap.length
&& this.heap[rightChildIndex]
> this.heap[largestIndex]) {
largestIndex = rightChildIndex;
}
if (index !== largestIndex) {
this.swap(index, largestIndex);
this.heapifyDown(largestIndex);
}
}
swap(i, j)
{
[this.heap[i], this.heap[j]] =
[ this.heap[j], this.heap[i] ];
}
}
// Driver's code:
const arr = [ 10, 5, 4, 3, 48, 6, 2, 33, 53, 10 ];
const K = 4;
// Function call
console.log(kthSmallest(arr, K));
Time Complexity: O(N * log(K)), The approach efficiently maintains a container of the K smallest elements while iterating through the array, ensuring a time complexity of O(N * log(K)), where N is the number of elements in the array.
Auxiliary Space: O(K)
[Alternative Approach 1] Using QuickSelect
QuickSelect is a selection algorithm based on the idea of QuickSort. Instead of sorting the whole array, it partitions the array and only recurses into the part that contains the k-th smallest element.
Steps:
- Choose a pivot element and partition the array around it.
- If the pivot’s index is equal to
k
, then the pivot is the k-th smallest element. - If the pivot’s index is greater than
k
, continue the search in the left subarray. - If the pivot’s index is less than
k
, continue the search in the right subarray. - Repeat this process until the k-th smallest element is found.
Please refer to the Quickselect article for the complete implementation.
Time Complexity : O(n^2) in the worst case, but on average works in O(n Log n) time and performs better than priority queue based algorithm.
Auxiliary Space : O(n) for recursion call stack in worst case. On average : O(Log n)
[Alternative Approach 2] Using Counting Sort
Counting sort is a linear time sorting algorithm that counts the occurrences of each element in an array and uses this information to determine the sorted order. The idea behind using counting sort to find the K'th smallest element is to use the counting phase, which essentially calculates the cumulative frequencies of elements. By tracking these cumulative frequencies, we can efficiently determine the K'th smallest element.
Note: This approach is particularly useful when the range of elements is small, this is because we are declaring a array of size maximum element. If the range of elements is very large, the counting sort approach may not be the most efficient choice.
Code Implementation:
C++
#include <iostream>
#include <vector>
using namespace std;
// This function returns the kth smallest element in a vector
int kthSmallest(vector<int>& v, int k)
{
// First, find the maximum element in the vector
int max_element = v[0];
for (int i = 1; i < v.size(); i++)
{
if (v[i] > max_element)
{
max_element = v[i];
}
}
// Create an array to store the frequency of each element
vector<int> freq(max_element + 1, 0);
for (int i = 0; i < v.size(); i++)
{
freq[v[i]]++;
}
// Keep track of the cumulative frequency of elements
int count = 0;
for (int i = 0; i <= max_element; i++)
{
if (freq[i] != 0)
{
count += freq[i];
if (count >= k)
{
// If we have seen k or more elements,
// return the current element
return i;
}
}
}
return -1;
}
int main()
{
vector<int> v = {12, 3, 5, 7, 19};
int k = 2;
cout << kthSmallest(v, k);
return 0;
}
Java
import java.util.ArrayList;
public class GFG {
// This function returns the 2nd smallest element in the array
static ArrayList<Integer> kthSmallest(int[] arr) {
// Use the size of the array directly
int n = arr.length;
// First, find the maximum element in the array
int max_element = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max_element) {
max_element = arr[i];
}
}
// Create an array to store the frequency of each element in the input array
int[] freq = new int[max_element + 1];
for (int i = 0; i < n; i++) {
freq[arr[i]]++;
}
// Keep track of the cumulative frequency of elements in the input array
int count = 0;
int result = -1;
for (int i = 0; i <= max_element; i++) {
if (freq[i] != 0) {
count += freq[i];
if (count >= 2) { // since we want the 2nd smallest
// If we have seen 2 or more elements, store the current element
result = i;
break;
}
}
}
// Return result inside an ArrayList
ArrayList<Integer> output = new ArrayList<>();
output.add(result);
return output;
}
// Driver Code
public static void main(String[] args) {
int[] arr = { 12, 3, 5, 7, 19 };
ArrayList<Integer> result = kthSmallest(arr);
System.out.println(result.get(0));
}
}
Python
# Python3 code for kth smallest element in an array
# function returns the kth smallest element in an array
def kth_smallest(arr, k):
# First, find the maximum element in the array
max_element = max(arr)
# Create a dictionary to store the frequency of each
# element in the input array
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
# Keep track of the cumulative frequency of elements
# in the input array
count = 0
for i in range(max_element + 1):
if i in freq:
count += freq[i]
if count >= k:
# If we have seen k or more elements,
# return the current element
return i
return -1
# Driver Code
arr = [12, 3, 5, 7, 19]
k = 2
print(kth_smallest(arr, k))
C#
using System;
using System.Collections.Generic;
class Program
{
// This function returns the kth smallest element in a list
static int KthSmallest(List<int> v, int k)
{
// First, find the maximum element in the list
int max_element = v[0];
for (int i = 1; i < v.Count; i++)
{
if (v[i] > max_element)
{
max_element = v[i];
}
}
// Create an array to store the frequency of each element
int[] freq = new int[max_element + 1];
for (int i = 0; i < v.Count; i++)
{
freq[v[i]]++;
}
// Keep track of the cumulative frequency of elements
int count = 0;
for (int i = 0; i <= max_element; i++)
{
if (freq[i] != 0)
{
count += freq[i];
if (count >= k)
{
// If we have seen k or more elements,
// return the current element
return i;
}
}
}
return -1;
}
static void Main()
{
List<int> v = new List<int> { 12, 3, 5, 7, 19 };
int k = 2;
Console.WriteLine(KthSmallest(v, k));
}
}
JavaScript
// This function returns the kth smallest element in an array
function kthSmallest(arr, k) {
// First, find the maximum element in the array
let max_element = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max_element) {
max_element = arr[i];
}
}
// Create an array to store the frequency of each element
let freq = new Array(max_element + 1).fill(0);
for (let i = 0; i < arr.length; i++) {
freq[arr[i]]++;
}
// Keep track of the cumulative frequency of elements
let count = 0;
for (let i = 0; i <= max_element; i++) {
if (freq[i] !== 0) {
count += freq[i];
if (count >= k) {
// If we have seen k or more elements,
// return the current element
return i;
}
}
}
return -1;
}
// Example usage
let arr = [12, 3, 5, 7, 19];
let k = 2;
console.log(kthSmallest(arr, k));
Time Complexity: O(N + max_element), where max_element is the maximum element of the array.
Auxiliary Space: O(max_element)
Related Articles:
Explore
Basics & Prerequisites
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem