K’th Smallest Element in Unsorted Array
Last Updated :
27 Jul, 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) auxiliary 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 array
int kthSmallest(int arr[], int N, int K)
{
// Sort the given array
sort(arr, arr + N);
// 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
cout << "K'th smallest element is "
<< kthSmallest(arr, N, 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("K'th smallest element is %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("K'th smallest element is "
+ 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("K'th smallest element is",
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("K'th smallest element"
+ " is " + 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("K'th smallest element is " + kthSmallest(arr, N, K));
PHP
<?php
// Simple PHP 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
sort($arr);
// Return k'th element
// in the sorted array
return $arr[$K - 1];
}
// Driver's Code
$arr = array(12, 3, 5, 7, 19);
$N =count($arr);
$K = 2;
// Function call
echo "K'th smallest element is ", kthSmallest($arr, $N, $K);
?>
OutputK'th smallest element is 5
Time Complexity: O(N log N)
Auxiliary Space: O(1)
[Expected Approach] Using Priority Queue(Max-Heap) - O(N * log(K)) time and O(K) auxiliary space:
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(int arr[], int N, int K)
{
// Create a max heap (priority queue)
priority_queue<int> pq;
// Iterate through the array elements
for (int i = 0; i < N; 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()
{
int N = 10;
int arr[N] = { 10, 5, 4, 3, 48, 6, 2, 33, 53, 10 };
int K = 4;
// Function call
cout << "Kth Smallest Element is: "
<< kthSmallest(arr, N, 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("Kth Smallest Element is: " + 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("Kth Smallest Element is:", kthSmallest(arr, K))
C#
using System;
using System.Collections.Generic;
public class KthSmallestElement
{
// Function to find the kth smallest array element
public static int KthSmallest(int[] arr, int K)
{
// Create a max heap (priority queue) using a SortedSet
var maxHeap = new SortedSet<int>(Comparer<int>.Create((a, b) => b.CompareTo(a)));
// Iterate through the array elements
foreach (var num in arr)
{
// Add the current element to the max heap
maxHeap.Add(-num);
// If the size of the max heap exceeds K, remove the largest element
if (maxHeap.Count > K)
maxHeap.Remove(maxHeap.Max);
}
// Return the Kth smallest element (top of the max heap)
return -maxHeap.Max;
}
// Driver's code:
public static void Main()
{
int[] arr = { 10, 5, 4, 3, 48, 6, 2, 33, 53, 10 };
int K = 4;
// Function call
Console.WriteLine("Kth Smallest Element is: " + 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("Kth Smallest Element is: " + kthSmallest(arr, K));
OutputKth Smallest Element is: 5
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)
[QuickSelect] Works best in Practice:
The algorithm is similar to QuickSort. The difference is, instead of recurring for both sides (after finding pivot), it recurs only for the part that contains the k-th smallest element. The logic is simple, if index of the partitioned element is more than k, then we recur for the left part. If index is the same as k, we have found the k-th smallest element and we return. If index is less than k, then we recur for the right part. This reduces the expected complexity from O(n log n) to O(n), with a worst-case of O(n^2).
function quickSelect(list, left, right, k)
if left = right
return list[left]
Select a pivotIndex between left and right
pivotIndex := partition(list, left, right,
pivotIndex)
if k = pivotIndex
return list[k]
else if k < pivotIndex
right := pivotIndex - 1
else
left := pivotIndex + 1
Please refer Quickselect for 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)
[Other Approach] Using Counting Sort (Not efficient for large range of elements)
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>
using namespace std;
// This function returns the kth smallest element in an array
int kthSmallest(int arr[], int n, int k) {
// 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[max_element + 1] = {0};
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;
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;
}
// Driver Code
int main() {
int arr[] = {12,3,5,7,19};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
cout << "The " << k << "th smallest element is " << kthSmallest(arr, n, k) << endl;
return 0;
}
Java
import java.util.Arrays;
public class GFG {
// This function returns the kth smallest element in an
// array
static int kthSmallest(int[] arr, int n, int k)
{
// 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];
Arrays.fill(freq, 0);
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;
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;
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 12, 3, 5, 7, 19 };
int n = arr.length;
int k = 2;
System.out.println("The " + k
+ "th smallest element is "
+ kthSmallest(arr, n, k));
}
}
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("The", k,"th smallest element is", kth_smallest(arr, k))
C#
using System;
public class GFG {
// This function returns the kth smallest element in an array
static int KthSmallest(int[] arr, int n, int k) {
// First, find the maximum element in the array
int maxElement = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > maxElement) {
maxElement = arr[i];
}
}
// Create an array to store the frequency of each
// element in the input array
int[] freq = new int[maxElement + 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;
for (int i = 0; i <= maxElement; 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;
}
// Driver Code
static void Main(string[] args) {
int[] arr = { 12, 3, 5, 7, 19 };
int n = arr.Length;
int k = 2;
Console.WriteLine("The " + k + "th smallest element is " + KthSmallest(arr, n, k));
}
}
JavaScript
// Function to find the kth smallest element in an array
function kthSmallest(arr, k) {
// First, find the maximum element in the array
let maxElement = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > maxElement) {
maxElement = arr[i];
}
}
// Create an array to store the frequency of each element in the input array
let freq = new Array(maxElement + 1).fill(0);
for (let i = 0; i < arr.length; i++) {
freq[arr[i]]++;
}
// Keep track of the cumulative frequency of elements in the input array
let count = 0;
for (let i = 0; i <= maxElement; 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; // kth smallest element not found
}
// Driver code
const arr = [12, 3, 5, 7, 19];
const k = 2;
console.log(`The ${k}th smallest element is ${kthSmallest(arr, k)}`);
OutputThe 2th smallest element is 5
Time Complexity: O(N + max_element), where max_element is the maximum element of the array.
Auxiliary Space: O(max_element)
Related Articles:
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA 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
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem