Loading section...

Top-K Largest and Smallest: The Canonical Pattern

Concepts: pyTopKLargest, pyTopKSmallest, pyHeapReplace

This is the most important heap pattern you will ever learn for interviews. Finding the top-K largest elements from a list of N elements. The naive approach: sort descending, take first K. O(n log n). The heap approach: maintain a min-heap of size exactly K. For every element you process, if it is larger than the heap's minimum (the root), push it in and pop the minimum out. At the end, the heap contains exactly the K largest elements. Time: O(n log k). Space: O(k). The Size-K Min-Heap Pattern for Top-K Largest This feels counterintuitive at first. You are finding the K LARGEST elements, but you are using a MIN-heap. Here is why: the min-heap keeps the K largest elements you have seen so far, and its root is the smallest of those K elements. That root is your eviction candidate. Every new