
Problem
Solution
Submissions
Kth Largest Element
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to find the kth largest element in an unsorted array. Note that it is the kth largest element in sorted order, not the kth distinct element. You can assume k is always valid, 1 ≤ k ≤ array's length. The algorithm should be efficient and handle large arrays.
Example 1
- Input: nums = [3,2,1,5,6,4], k = 2
- Output: 5
- Explanation:
- Sort the array in descending order: [6,5,4,3,2,1].
- The 1st largest element is 6.
- The 2nd largest element is 5.
- Therefore, the 2nd largest element is 5.
- Sort the array in descending order: [6,5,4,3,2,1].
Example 2
- Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
- Output: 4
- Explanation:
- Sort the array in descending order: [6,5,5,4,3,3,2,2,1].
- The 1st largest is 6, 2nd largest is 5, 3rd largest is 5.
- The 4th largest element is 4.
- Note that we count duplicates as separate elements.
- Sort the array in descending order: [6,5,5,4,3,3,2,2,1].
Constraints
- 1 ≤ k ≤ nums.length ≤ 10^5
- -10^4 ≤ nums[i] ≤ 10^4
- k is always valid
- Time Complexity: O(n log k) or O(n) average case
- Space Complexity: O(k) or O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a min heap of size k to efficiently find the kth largest element
- Iterate through the array and maintain only k largest elements in the heap
- If heap size exceeds k, remove the smallest element from the heap
- The root of the min heap will be the kth largest element
- Alternatively, use quickselect algorithm for O(n) average time complexity
- Another approach is to sort the array and return the element at index (length - k)