Algorithm Day75 - Kth Largest Element in an Array
π§© Problem Description
Given an integer array nums
and an integer k
, return the k-th largest element in the array.
Note: It is the k-th largest element in the sorted order, not the k-th distinct element.
π¬ Examples
Example 1
1 | Input: nums = [3,2,1,5,6,4], k = 2 |
Example 2
1 | Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 |
π‘ Intuition
There are two common approaches:
Heap (Min-Heap of size k):
- Maintain a heap of the largest k elements.
- The root of the heap is the answer.
- Time: O(n log k).
Quickselect (Hoareβs selection algorithm):
- Similar to quicksort partitioning.
- Average time: O(n), worst-case O(nΒ²).
- More efficient in practice.
π’ Java Code (Heap)
1 | import java.util.*; |
π’ Java Code (Quickselect)
1 | class Solution { |
β± Complexity Analysis
Heap Solution
- Time: O(n log k)
- Space: O(k)
Quickselect Solution
- Time: O(n) on average, O(nΒ²) worst-case
- Space: O(1)
βοΈ Summary
- Use min-heap for simplicity.
- Use quickselect for optimal performance on average.
Related problems
lc-347
β Top K Frequent Elementslc-973
β K Closest Points to Originlc-703
β Kth Largest Element in a Stream