Kth Largest Element in an Array
Master this topic with zero to advance depth.
Kth Largest Element in an Array
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.
Visual Representation
nums = [3,2,1,5,6,4], k = 2
Min-Heap (size k=2):
[1] -> [1, 2] -> [2, 3] -> [3, 5] -> [5, 6] -> [5, 6] (after 4)
Heap top is 5th largest.
Quickselect (Partitions):
[3, 2, 1, 5, 6, 4] -> pivot 4
[3, 2, 1] | [4] | [5, 6]
Target index is in the right partition.Examples
Level I: Sorting (Naive)
Intuition
The simplest way is to sort the entire array in descending order and return the element at index k-1.
Thought Process
- Sort the input array.
- Access the element at
length - k(for ascending sort) ork - 1(for descending sort).
Detailed Dry Run
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4
- Sorted: [1, 2, 2, 3, 3, 4, 5, 5, 6]
- Index (9 - 4) = 5
- nums[5] = 4
Level II: Quickselect (Average Case Optimal)
Intuition
Based on the Partition logic of Quicksort. We only care about the partition that contains the th largest element (index ).
Thought Process
- Choose a pivot element.
- Partition the array around the pivot like in Quicksort.
- Compare the pivot's final index with target index .
- Recurse into the sub-array containing the target index.
Detailed Dry Run
nums = [3, 2, 1, 5, 6, 4], k = 2, target = 6-2 = 4
- Partition: [3, 2, 1, 4, 6, 5], 4 is at index 3.
- 3 < 4: Recurse [6, 5]
- Partition: [5, 6], 6 is at index 5.
- 5 > 4: Recurse [5]
- Index 4 is 5. Return 5.
Level III: Min-Heap (Optimal)
Intuition
Maintain a Min-Heap of size k. As we iterate through the array, if we find an element larger than the heap's minimum, we replace the minimum with it. After one pass, the heap contains the k largest elements, and the top is the kth largest.
Thought Process
- Initialize a Min-Heap.
- For each number in
nums:- Push to heap.
- If heap size >
k, pop the smallest element.
- The root of the heap is our answer.
Detailed Dry Run
nums = [3, 2, 1, 5, 6, 4], k = 2
- Push 3: Heap [3]
- Push 2: Heap [2, 3]
- Push 1: Heap [1, 2, 3] -> Pop 1. Heap [2, 3]
- Push 5: Heap [2, 3, 5] -> Pop 2. Heap [3, 5]
- Push 6: Heap [3, 5, 6] -> Pop 3. Heap [5, 6]
- Push 4: Heap [4, 5, 6] -> Pop 4. Heap [5, 6] Result: Top is 5
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.