Find the k-th largest element in an array
Company: LinkedIn
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency with selection algorithms, array manipulation, and analysis of time and space complexity, reflecting competency in order-statistics and basic data structures.
Constraints
- 1 <= len(nums) <= 2 * 10^5
- -10^9 <= nums[i] <= 10^9
- 1 <= k <= len(nums)
Examples
Input: ([3, 2, 1, 5, 6, 4], 2)
Expected Output: 5
Explanation: Descending: [6,5,4,3,2,1]; the 2nd largest is 5.
Input: ([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)
Expected Output: 4
Explanation: Descending: [6,5,5,4,3,3,2,2,1]; the 4th element is 4 (duplicates count toward rank).
Input: ([1], 1)
Expected Output: 1
Explanation: Single element; the 1st largest is itself.
Input: ([7, 7, 7, 7], 2)
Expected Output: 7
Explanation: All duplicates; every rank is 7.
Input: ([-1, -2, -3, -4, -5], 1)
Expected Output: -1
Explanation: All negatives; the largest (1st) is -1.
Input: ([-10, 0, 10, 5, -5], 3)
Expected Output: 0
Explanation: Descending: [10,5,0,-5,-10]; the 3rd largest is 0.
Input: ([2, 1], 2)
Expected Output: 1
Explanation: k equals array length; the k-th largest is the smallest element, 1.
Hints
- You don't need to fully sort the array. To find the k-th largest, you only need to track the k largest elements seen so far.
- A min-heap of size k works well: push elements and pop the smallest whenever the heap exceeds size k. After processing all elements, the heap root is the k-th largest. This is O(n log k).
- For optimal average performance, use Quickselect (partition-based selection) to find the element at index (n - k) in ascending order, giving O(n) average time.
- Watch the indexing: the k-th LARGEST in descending order equals the element at 0-based index (n - k) when sorted ascending. Duplicates count toward the rank.