1. Min-Heap of Size K (Streaming Pattern)
OptimalMaintain a Min-Heap of capacity K. Stream numbers into the heap and pop the smallest whenever size exceeds K. The root will always hold the Kth largest element in O(n log k) time.
Each of the N elements is pushed into a heap of size at most K. Heap push and pop operations take O(log k) time. For k << n, this is much faster than full sorting O(n log n).
The min-heap stores at most K + 1 elements at any point in time.
How It Works
The Invariant: The Bounded VIP Lounge
Instead of sorting the entire array of size N in O(n log n) time, think of a VIP room that only holds K people:
- A Min-Heap keeps the smallest of its current members at the top (
root) in O(1) peek time. - For each number
numinnums:
- Push
numinto the Min-Heap. - If the heap size exceeds
k, pop the top element. - What was popped? The smallest value among the top K + 1 elements!
- After processing all N elements, the heap contains the K largest elements seen across the entire array.
- Who is at the top of this Min-Heap? The smallest among the K largest elements — which is mathematically the Kth largest element!
Why Engineers Love This in Production
This approach is a streaming algorithm. If the input stream contains 10 billion numbers but you only need the Top-10 (k = 10), you do not need to store 10 billion items in memory! You only need a 10-element heap, using O(k) space regardless of stream length.
Step-by-Step Dry Run
Initialize empty Min-Heap of capacity 2. Stream elements one by one.
heap = []- +Optimal O(k) memory footprint
- +Streams data without needing all items in memory simultaneously
- -O(n log k) runtime is slower than average-O(n) Quickselect when k is near n/2
Reference Implementation
Complete implementation for Min-Heap of Size K (Streaming Pattern) in Python, JavaScript, Java, C++, and C.
import heapqdef find_kth_largest(nums: list[int], k: int) -> int:min_heap = []for num in nums:heapq.heappush(min_heap, num)if len(min_heap) > k:heapq.heappop(min_heap)return min_heap[0]if __name__ == "__main__":test1 = [3, 2, 1, 5, 6, 4]k1 = 2test2 = [3, 2, 3, 1, 2, 4, 5, 5, 6]k2 = 4print("test1 2nd largest:", find_kth_largest(test1, k1))print("test2 4th largest:", find_kth_largest(test2, k2))
function findKthLargest(nums, k) {
// Min-heap simulation using binary heap array
const heap = [];
function push(val) {
heap.push(val);
let idx = heap.length - 1;
while (idx > 0) {
const parent = Math.floor((idx - 1) / 2);
if (heap[parent] <= heap[idx]) break;
[heap[parent], heap[idx]] = [heap[idx], heap[parent]];
idx = parent;
}
}
function pop() {
const min = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let idx = 0;
while (true) {
let left = 2 * idx + 1;
let right = 2 * idx + 2;
let smallest = idx;
if (left < heap.length && heap[left] < heap[smallest]) smallest = left;
if (right < heap.length && heap[right] < heap[smallest]) smallest = right;
if (smallest === idx) break;
[heap[idx], heap[smallest]] = [heap[smallest], heap[idx]];
idx = smallest;
}
}
return min;
}
for (let i = 0; i < nums.length; i++) {
push(nums[i]);
if (heap.length > k) {
pop();
}
}
return heap[0];
}
const test1 = [3, 2, 1, 5, 6, 4];
console.log("2nd largest:", findKthLargest(test1, 2));import java.util.PriorityQueue;
public class Solution {
public static int findKthLargest(int[] nums, int k) {
// PriorityQueue is a Min-Heap by default in Java
PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
for (int num : nums) {
minHeap.offer(num);
if (minHeap.size() > k) {
minHeap.poll();
}
}
return minHeap.peek();
}
public static void main(String[] args) {
int[] test1 = { 3, 2, 1, 5, 6, 4 };
int[] test2 = { 3, 2, 3, 1, 2, 4, 5, 5, 6 };
System.out.println("2nd largest: " + findKthLargest(test1, 2));
System.out.println("4th largest: " + findKthLargest(test2, 4));
}
}#include <iostream>
#include <vector>
#include <queue>
int findKthLargest(const std::vector<int>& nums, int k) {
// std::greater<int> creates a Min-Heap
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
for (int num : nums) {
minHeap.push(num);
if (static_cast<int>(minHeap.size()) > k) {
minHeap.pop();
}
}
return minHeap.top();
}
int main() {
std::vector<int> test1 = {3, 2, 1, 5, 6, 4};
std::vector<int> test2 = {3, 2, 3, 1, 2, 4, 5, 5, 6};
std::cout << "2nd largest: " << findKthLargest(test1, 2) << "\n";
std::cout << "4th largest: " << findKthLargest(test2, 4) << "\n";
return 0;
}#include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void minHeapify(int heap[], int size, int i) {
int smallest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < size && heap[left] < heap[smallest]) smallest = left;
if (right < size && heap[right] < heap[smallest]) smallest = right;
if (smallest != i) {
swap(&heap[i], &heap[smallest]);
minHeapify(heap, size, smallest);
}
}
int findKthLargest(int* nums, int numsSize, int k) {
int* heap = (int*)malloc(k * sizeof(int));
for (int i = 0; i < k; i++) {
heap[i] = nums[i];
}
// Build min heap of first k elements
for (int i = k / 2 - 1; i >= 0; i--) {
minHeapify(heap, k, i);
}
// Process remaining elements
for (int i = k; i < numsSize; i++) {
if (nums[i] > heap[0]) {
heap[0] = nums[i];
minHeapify(heap, k, 0);
}
}
int result = heap[0];
free(heap);
return result;
}
int main(void) {
int test1[] = {3, 2, 1, 5, 6, 4};
int test2[] = {3, 2, 3, 1, 2, 4, 5, 5, 6};
printf("2nd largest: %d\n", findKthLargest(test1, 6, 2));
printf("4th largest: %d\n", findKthLargest(test2, 9, 4));
return 0;
}