Understanding the Problem
We are given an unsorted array and a number k
. Our goal is to find the kth
smallest element in the array.
Let’s understand this with an example:
Input: arr = [7, 10, 4, 3, 20, 15], k = 3
Output: 7
If we sorted the array, it would become: [3, 4, 7, 10, 15, 20]
. The 3rd smallest element is 7
.
But sorting the entire array takes O(n log n)
time. We want to find the answer more efficiently.
Approach: Quickselect Algorithm
The Quickselect algorithm helps us find the kth
smallest element in average O(n)
time — without sorting the whole array.
How Quickselect Works
We follow these steps:
- Choose a pivot element from the array (usually random).
- Partition the array into three parts:
lows
: elements less than the pivot
pivots
: elements equal to the pivot
highs
: elements greater than the pivot
- Now compare
k
with the sizes of these parts:
- If
k ≤ size of lows
, then the answer lies in the lows
part. Recur on that.
- If
k ≤ size of lows + size of pivots
, the pivot itself is the kth
smallest element.
- Else, the answer lies in the
highs
part. Recur on highs
with k - size of lows - size of pivots
.
Let’s Visualize With the Same Example
arr = [7, 10, 4, 3, 20, 15], k = 3
- Choose pivot = 7
- Partition: lows = [4, 3], pivots = [7], highs = [10, 20, 15]
- lows has 2 elements, pivots has 1 → total = 3
- Since k = 3 is within (2 + 1), return pivot = 7
Handling Edge Cases
Case 1: Empty array
If the input array is empty, there's no element to find. Return -1
.
Case 2: k is out of bounds
If k < 1
or k > length of array
, return -1
.
Case 3: Array has duplicates
The algorithm works even if duplicates exist because it separates values equal to the pivot.
Case 4: Array has one element
If the array has only one value and k = 1
, then return that element directly.
Why This Is Efficient
Unlike full sorting, which looks at every element multiple times, Quickselect repeatedly focuses only on the part of the array where the answer could be. This smart narrowing saves time.
That’s how we solve the problem of finding the kth
smallest element — step by step, clearly and efficiently!
Comments
Loading comments...