Kth Largest Element in an Array
Find the kth largest element in an unsorted array. The premier problem for learning Min-Heap bounded tracking and Quickselect partitioning.
Problem Statement
Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
Can you solve it without sorting?
Examples & Constraints
- 1 <= k <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
Min-Heap of Size K (Streaming Pattern)
Optimal ApproachMaintain 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.
Underlying algorithmic logic
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 execution walkthrough
Initialize empty Min-Heap of capacity 2. Stream elements one by one.
Push 3 then 2. Heap size is 2. Top (smallest) is 2.
Push 1 -> heap = [1, 3, 2]. Size exceeds 2! Pop root (1).
Push 5, pop 2 -> [3, 5]. Push 6, pop 3 -> [5, 6]. Push 4, pop 4 -> [5, 6].
- •Optimal O(k) memory footprint
- •Streams data without requiring all items in memory simultaneously
- •O(n log k) runtime is slightly slower than optimal average O(n) Quickselect
Code Implementations
Ready-to-useCopy & paste production-ready solutions for Min-Heap of Size K (Streaming Pattern) in your language of choice
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))
Understand Heap & Priority Queue Visually
Understand min and max heap properties, tree structure balance, and heapify up/down actions. Test live edge cases and watch memory state transitions step-by-step.
Frequently Asked Questions
Related Logic & Algorithm Problems
Contains Duplicate
Determine if any value appears at least twice in an integer array. A foundational problem for mastering constant-time hash lookups vs sorting trade-offs.
Two Sum
Find the two numbers in an array that sum up to a target value. The quintessential problem for learning how to trade memory for speed using a Hash Map.
Valid Anagram
Determine whether two strings have the exact same character frequencies. A core problem demonstrating the power of fixed-size frequency buckets over O(n log n) sorting.