Kth Smallest Element Using Min Heap in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to find the kth smallest element using a min heap changes as the input size grows.
Specifically, how does the number of steps grow when we add more numbers or change k?
Analyze the time complexity of the following code snippet.
function kthSmallest(arr: number[], k: number): number {
const minHeap = new MinHeap();
for (const num of arr) {
minHeap.insert(num);
}
let result = -1;
for (let i = 0; i < k; i++) {
result = minHeap.extractMin();
}
return result;
}
This code builds a min heap from the array, then extracts the smallest element k times to find the kth smallest.
- Primary operation: Inserting all n elements into the min heap and extracting the minimum k times.
- How many times: Insert runs n times; extractMin runs k times.
As the input size n grows, building the heap takes more steps, and extracting k times adds more steps depending on k.
| Input Size (n) | Approx. Operations |
|---|---|
| 10, k=3 | About 10 insertions + 3 extractions |
| 100, k=10 | About 100 insertions + 10 extractions |
| 1000, k=100 | About 1000 insertions + 100 extractions |
Pattern observation: The total steps grow roughly with n plus k, but each insertion and extraction takes a small extra time that grows with the heap size.
Time Complexity: O(n log n + k log n)
This means the time grows mostly by inserting all n elements into the heap and then extracting k times, each operation taking time related to the heap size.
[X] Wrong: "Building the heap is just O(n) so the whole process is O(n + k)."
[OK] Correct: While heap construction can be done in O(n), each insertion here is done one by one, costing O(log n) each, so total insertion is O(n log n). Also, each extraction costs O(log n), so k extractions add up.
Understanding this time complexity helps you explain why heaps are useful for selection problems and shows your grasp of how data structures affect performance.
"What if we used a max heap of size k instead of a min heap of size n? How would the time complexity change?"
Practice
kth smallest element using a min heap?Solution
Step 1: Understand min heap property
A min heap always keeps the smallest element at the root, so extracting the root gives the smallest element.Step 2: Extract minimum
By extracting the rootktimesktimes, we get thekthsmallest element.Final Answer:
Build a min heap and extract minimumktimes -> Option BQuick Check:
Min heap extraction = kth smallest element [OK]
- Using max heap instead of min heap
- Sorting array instead of using heap
- Extracting less or more than k times
Solution
Step 1: Understand comparator for min heap
A min heap comparator returns negative if first argument is smaller, so(a, b) => a - bis correct.Step 2: Check code options
const minHeap = new PriorityQueue<number>((a, b) => a - b); uses(a, b) => a - b, which creates a min heap. const minHeap = new PriorityQueue<number>((a, b) => b - a); reverses order, making max heap.Final Answer:
const minHeap = new PriorityQueue<number>((a, b) => a - b); -> Option AQuick Check:
Comparator a-b creates min heap [OK]
- Using max heap comparator for min heap
- Using wrong class name for min heap
- Confusing comparator logic
const arr = [7, 10, 4, 3, 20, 15];
const k = 3;
// Build min heap
const minHeap = new MinPriorityQueue<number>();
arr.forEach(num => minHeap.enqueue(num));
let kthSmallest = -1;
for (let i = 0; i < k; i++) {
kthSmallest = minHeap.dequeue().element;
}
console.log(kthSmallest);Solution
Step 1: Insert all elements into min heap
Min heap will organize elements so smallest is at root: 3, 4, 7, 10, 15, 20.Step 2: Extract min element k=3 times
Extract 1: 3, Extract 2: 4, Extract 3: 7. So kth smallest is 7.Final Answer:
7 -> Option AQuick Check:
3rd smallest in array = 7 [OK]
- Confusing kth smallest with kth largest
- Off-by-one error in loop
- Not building min heap correctly
function kthSmallest(arr: number[], k: number): number {
const minHeap = new MinPriorityQueue<number>();
for (let i = 0; i <= arr.length; i++) {
minHeap.enqueue(arr[i]);
}
let result = -1;
for (let j = 0; j < k; j++) {
result = minHeap.dequeue().element;
}
return result;
}Solution
Step 1: Check array loop bounds
The loop usesi <= arr.length, which accessesarr[arr.length]undefined, causing error.Step 2: Correct loop condition
Change toi < arr.lengthto avoid out-of-bounds access.Final Answer:
Loop condition should be i < arr.length to avoid undefined enqueue -> Option CQuick Check:
Array index out of bounds causes error [OK]
i < arr.length to avoid out-of-bounds errors [OK]- Using <= instead of < in loops
- Confusing min heap with max heap
- Incorrect dequeue loop count
kth smallest unique element?Solution
Step 1: Remove duplicates using a hash set
Duplicates can cause incorrect counting of unique elements, so first filter unique elements.Step 2: Build min heap from unique elements and extract kth smallest
After filtering, build min heap and extractktimes to get kth smallest unique element.Final Answer:
Use a hash set to filter unique elements first, then build a min heap -> Option DQuick Check:
Filter duplicates before heap for unique kth smallest [OK]
- Ignoring duplicates causing wrong kth element
- Using max heap incorrectly
- Extracting without filtering unique elements
Ready to prove it?
Pass the test and this pattern moves unknown
