Kth Smallest Element Using Min Heap in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to find the kth smallest element grows as the input size changes.
Specifically, how the operations scale when using a min heap to solve this problem.
Analyze the time complexity of the following code snippet.
function kthSmallest(arr, k) {
const minHeap = new MinHeap();
for (const num of arr) {
minHeap.insert(num);
}
let result;
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.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Inserting all elements into the min heap and extracting the minimum k times.
- How many times: Insert runs n times (for all elements), extractMin runs k times.
Building the heap takes time proportional to the number of elements, and extracting k times adds more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 insertions + k extractions, each operation costs a few steps. |
| 100 | About 100 insertions + k extractions, more steps but still manageable. |
| 1000 | About 1000 insertions + k extractions, operations grow but remain efficient. |
Pattern observation: The total work grows roughly linearly with n for building, plus extra work proportional to k for extraction.
Time Complexity: O(n log n + k log n)
This means the time grows mostly with n times log n for building the heap, plus k times log n for extracting elements.
[X] Wrong: "Building the heap is just O(n) so total time is O(n + k)."
[OK] Correct: Building a heap by inserting elements one by one costs O(n log n), because each insertion takes log n time. So total time is more than just O(n).
Understanding how heap operations add up helps you explain your solution clearly and shows you know how data structures affect performance.
"What if we used a max heap of size k instead of a min heap for all n elements? How would the time complexity change?"
Practice
Kth Smallest Element Using Min Heap algorithm primarily do?Solution
Step 1: Understand the min heap role
A min heap always keeps the smallest element at the root, making it easy to access the smallest values.Step 2: Use min heap to find Kth smallest
By extracting the root K times, we get the Kth smallest element.Final Answer:
Find the element that is the Kth smallest in a list using a min heap -> Option AQuick Check:
Kth smallest element = find using min heap [OK]
- Confusing min heap with max heap
- Thinking it sorts the entire list
- Assuming it finds the largest element
Solution
Step 1: Insert element at the end
Inserting into a heap means adding the element at the end of the array.Step 2: Restore heap property by heapify up
After insertion, heapify up is called from the inserted index to maintain min heap order.Final Answer:
heap.push(element); heapifyUp(heap.length - 1); -> Option BQuick Check:
Insert + heapifyUp = heap.push(element); heapifyUp(heap.length - 1); [OK]
- Using pop or shift to insert elements
- Calling heapifyDown after insertion
- Inserting at the front of the array
const heap = [1, 3, 6, 5, 9, 8];
function extractMin(heap) {
const min = heap[0];
heap[0] = heap.pop();
heapifyDown(heap, 0);
return min;
}
function heapifyDown(heap, i) {
const left = 2 * i + 1;
const right = 2 * i + 2;
let smallest = i;
if (left < heap.length && heap[left] < heap[smallest]) smallest = left;
if (right < heap.length && heap[right] < heap[smallest]) smallest = right;
if (smallest !== i) {
[heap[i], heap[smallest]] = [heap[smallest], heap[i]];
heapifyDown(heap, smallest);
}
}
console.log(extractMin(heap));Solution
Step 1: Extract min element
The min element is at heap[0], which is 1.Step 2: Replace root and heapify down
Replace root with last element 8, then heapify down to restore min heap.Final Answer:
1 -> Option DQuick Check:
extractMin returns root = 1 [OK]
- Returning last element instead of root
- Not heapifying down after extraction
- Confusing min heap root with max
function kthSmallest(arr, k) {
const heap = [];
for (const num of arr) {
heap.push(num);
}
for (let i = Math.floor(heap.length / 2); i >= 0; i--) {
heapifyDown(heap, i);
}
let result;
for (let i = 0; i < k; i++) {
result = heap.shift();
heapifyDown(heap, 0);
}
return result;
}Solution
Step 1: Check element removal method
Using shift() removes first element but shifts all others, breaking heap structure.Step 2: Correct removal method
Should remove root by swapping with last element, popping last, then heapify down.Final Answer:
Using shift() removes first element but does not maintain heap structure -> Option AQuick Check:
shift() breaks heap property [OK]
- Using shift() instead of swap and pop
- Incorrect heap building loop range
- Ignoring heapify after removal
[7, 10, 4, 3, 20, 15] and k = 3, what is the Kth smallest element using a min heap approach?Solution
Step 1: Build min heap from array
Min heap root is smallest element: 3.Step 2: Extract min 3 times
Extract 1st min: 3, 2nd min: 4, 3rd min: 7.Final Answer:
7 -> Option CQuick Check:
3rd smallest element = 7 [OK]
- Counting index instead of extraction times
- Confusing Kth smallest with Kth largest
- Not building min heap properly
Ready to prove it?
Pass the test and this pattern moves unknown
