Arrays January 18 ,2026

Kth Smallest Element in an Array

Problem Statement

You are given an integer array arr and an integer k.

Your task is to find the k-th smallest element in the array.

1 ≤ k ≤ n

Example 1

Input

arr = [7,10,4,3,20,15]
k = 3

Output

7

Example 2

Input

arr = [3,2,1,5,6,4]
k = 2

Output

2

Why This Problem Is Important

  • Extremely frequent interview question
  • Tests sorting, heap, partition logic
  • Introduces QuickSelect (selection algorithm)
  • Asked in FAANG, Amazon, Microsoft, Adobe
  • Foundation for Top K / Order Statistics

Approach 1: Sorting

Idea

Sort the array and return the element at index k-1.

Algorithm

  1. Sort the array
  2. Return arr[k-1]

Time & Space Complexity

  • Time: O(n log n)
  • Space: O(1) (in-place sort)

 

Implementations

C++

#include 
using namespace std;

int main() {
    int arr[] = {7,10,4,3,20,15};
    int k = 3, n = 6;

    sort(arr, arr+n);
    cout << arr[k-1];
    return 0;
}

Java

import java.util.*;

public class KthSmallest {
    public static void main(String[] args) {
        int[] arr = {7,10,4,3,20,15};
        int k = 3;

        Arrays.sort(arr);
        System.out.println(arr[k-1]);
    }
}

Python

arr = [7,10,4,3,20,15]
k = 3

arr.sort()
print(arr[k-1])

JavaScript

let arr = [7,10,4,3,20,15];
let k = 3;

arr.sort((a,b)=>a-b);
console.log(arr[k-1]);

C#

using System;

class Program {
    static void Main() {
        int[] arr = {7,10,4,3,20,15};
        int k = 3;

        Array.Sort(arr);
        Console.WriteLine(arr[k-1]);
    }
}

Output

7

Approach 2: Min Heap

Idea

Insert all elements into a min heap, remove k-1 elements, and the top is the answer.

Algorithm

  1. Build min heap from array
  2. Pop k-1 elements
  3. Return top element

Time & Space Complexity

  • Time: O(n + k log n)
  • Space: O(n)

Implementations

C++

#include 
using namespace std;

int main() {
    vector arr = {7,10,4,3,20,15};
    int k = 3;

    priority_queue, greater> pq(arr.begin(), arr.end());

    for(int i = 1; i < k; i++)
        pq.pop();

    cout << pq.top();
    return 0;
}

Java

import java.util.*;

public class KthSmallest {
    public static void main(String[] args) {
        int[] arr = {7,10,4,3,20,15};
        int k = 3;

        PriorityQueue pq = new PriorityQueue<>();
        for(int x : arr) pq.add(x);

        for(int i = 1; i < k; i++)
            pq.poll();

        System.out.println(pq.peek());
    }
}

Python

import heapq

arr = [7,10,4,3,20,15]
k = 3

heapq.heapify(arr)
for _ in range(k-1):
    heapq.heappop(arr)

print(arr[0])

JavaScript

// Using simple sort to simulate min-heap behavior
let arr = [7,10,4,3,20,15];
let k = 3;

arr.sort((a,b)=>a-b);
console.log(arr[k-1]);

C#

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        int[] arr = {7,10,4,3,20,15};
        int k = 3;

        PriorityQueue pq = new PriorityQueue();
        foreach(int x in arr)
            pq.Enqueue(x, x);

        for(int i = 1; i < k; i++)
            pq.Dequeue();

        Console.WriteLine(pq.Peek());
    }
}

Output

7

Approach 3: Max Heap (Size k)

Idea

Maintain a max heap of size k.
If heap size exceeds k, remove the largest element.

Algorithm

  1. Traverse array
  2. Push element into max heap
  3. If heap size > k, pop
  4. Heap top is answer

Time & Space Complexity

  • Time: O(n log k)
  • Space: O(k)

C++

#include 
using namespace std;

int main() {
    int arr[] = {7,10,4,3,20,15};
    int n = 6, k = 3;

    priority_queue pq;
    for(int i = 0; i < n; i++) {
        pq.push(arr[i]);
        if(pq.size() > k)
            pq.pop();
    }

    cout << pq.top();
    return 0;
}

Java

import java.util.*;

public class KthSmallest {
    public static void main(String[] args) {
        int[] arr = {7,10,4,3,20,15};
        int k = 3;

        PriorityQueue pq =
            new PriorityQueue<>(Collections.reverseOrder());

        for(int x : arr) {
            pq.add(x);
            if(pq.size() > k)
                pq.poll();
        }
        System.out.println(pq.peek());
    }
}

Python

import heapq

arr = [7,10,4,3,20,15]
k = 3
heap = []

for x in arr:
    heapq.heappush(heap, -x)
    if len(heap) > k:
        heapq.heappop(heap)

print(-heap[0])

JavaScript

// Simulating max heap using sorting (since JS lacks built-in heap)
let arr = [7,10,4,3,20,15];
let k = 3;

let heap = [];

for (let x of arr) {
    heap.push(x);
    heap.sort((a,b)=>b-a); // max heap behavior
    if (heap.length > k)
        heap.pop();
}

console.log(heap[0]);

C#

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        int[] arr = {7,10,4,3,20,15};
        int k = 3;

        PriorityQueue pq =
            new PriorityQueue();

        foreach(int x in arr) {
            pq.Enqueue(x, -x); // max heap using negative priority
            if(pq.Count > k)
                pq.Dequeue();
        }

        Console.WriteLine(pq.Peek());
    }
}

Output

7

Approach 4: QuickSelect (Optimal)

Idea

Based on QuickSort partitioning, but only processes one side.

Algorithm

  1. Choose pivot
  2. Partition array
  3. If pivot index == k-1 → answer
  4. Else recurse left or right

Time & Space Complexity

  • Time: O(n) average
  • Space: O(1)

C++

#include 
using namespace std;

int partition(int arr[], int l, int r) {
    int pivot = arr[r];
    int i = l;
    for(int j = l; j < r; j++) {
        if(arr[j] <= pivot) {
            swap(arr[i], arr[j]);
            i++;
        }
    }
    swap(arr[i], arr[r]);
    return i;
}

int quickSelect(int arr[], int l, int r, int k) {
    if(l <= r) {
        int p = partition(arr, l, r);
        if(p == k) return arr[p];
        else if(p > k) return quickSelect(arr, l, p-1, k);
        else return quickSelect(arr, p+1, r, k);
    }
    return -1;
}

int main() {
    int arr[] = {7,10,4,3,20,15};
    int n = 6, k = 3;

    cout << quickSelect(arr, 0, n-1, k-1);
    return 0;
}

Java

import java.util.*;

public class KthSmallestQuickSelect {

    static int partition(int[] arr, int l, int r) {
        int pivot = arr[r];
        int i = l;
        for(int j = l; j < r; j++) {
            if(arr[j] <= pivot) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
            }
        }
        int temp = arr[i];
        arr[i] = arr[r];
        arr[r] = temp;
        return i;
    }

    static int quickSelect(int[] arr, int l, int r, int k) {
        if(l <= r) {
            int p = partition(arr, l, r);
            if(p == k) return arr[p];
            else if(p > k) return quickSelect(arr, l, p-1, k);
            else return quickSelect(arr, p+1, r, k);
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {7,10,4,3,20,15};
        int k = 3;
        System.out.println(quickSelect(arr, 0, arr.length-1, k-1));
    }
}

Python

def quickselect(arr, k):
    pivot = arr[len(arr)//2]
    left = [x for x in arr if x < pivot]
    mid = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]

    if k <= len(left):
        return quickselect(left, k)
    elif k <= len(left) + len(mid):
        return pivot
    else:
        return quickselect(right, k - len(left) - len(mid))

arr = [7,10,4,3,20,15]
k = 3
print(quickselect(arr, k))

JavaScript

function quickSelect(arr, k) {
    if (arr.length === 1) return arr[0];

    let pivot = arr[Math.floor(arr.length / 2)];
    let left = arr.filter(x => x < pivot);
    let mid = arr.filter(x => x === pivot);
    let right = arr.filter(x => x > pivot);

    if (k <= left.length)
        return quickSelect(left, k);
    else if (k <= left.length + mid.length)
        return pivot;
    else
        return quickSelect(right, k - left.length - mid.length);
}

let arr = [7,10,4,3,20,15];
let k = 3;
console.log(quickSelect(arr, k));

C#

using System;
using System.Linq;

class Program {

    static int QuickSelect(int[] arr, int k) {
        int pivot = arr[arr.Length / 2];

        var left = arr.Where(x => x < pivot).ToArray();
        var mid = arr.Where(x => x == pivot).ToArray();
        var right = arr.Where(x => x > pivot).ToArray();

        if (k <= left.Length)
            return QuickSelect(left, k);
        else if (k <= left.Length + mid.Length)
            return pivot;
        else
            return QuickSelect(right, k - left.Length - mid.Length);
    }

    static void Main() {
        int[] arr = {7,10,4,3,20,15};
        int k = 3;
        Console.WriteLine(QuickSelect(arr, k));
    }
}

Output

7

Summary

  • Sorting is simplest but slower
  • Heaps are best for streaming / large data
  • Max Heap (k size) is very efficient
  • QuickSelect is interview favorite

 

Next Problem in the Series

Maximum Length Bitonic Subarray
 

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com