Find kth largest element in array
MetaSoftware Engineer · OnsiteLast updated
A classic Meta software engineer onsite coding question: return the k-th largest element from an unsorted integer array, handling duplicates correctly. It tests order statistics and selection algorithms — sort, size-k min-heap (O(n log k)), and quickselect (O(n) average) — and the candidate's ability to beat a full sort.
Question
Given an unsorted array of integers nums and an integer k, return the k-th largest element in the array.
The 1st largest element is the maximum element, the 2nd largest is the second highest, and so on. Equivalently, the k-th largest element is the value that would appear at index k - 1 if the array were sorted in descending order.
Requirements:
- Handle duplicates correctly. Duplicates count as separate positions, e.g.
nums = [5, 5, 4],k = 2returns5(not4). - Describe your approach and analyze its time and space complexity. Try to design an algorithm that is more efficient than fully sorting the array. (You do not need to provide working code unless asked.)
Input:
nums: an array of integersk: an integer where1 <= k <= len(nums)
Output:
- The k-th largest element (an integer).
Constraints (typical interview scale):
1 <= n <= 2 * 10^5-10^9 <= nums[i] <= 10^9
Example:
nums = [3, 2, 1, 5, 6, 4],k = 2->5nums = [5, 5, 4],k = 2->5
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.