
Problem
Solution
Submissions
Kth Largest Element
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C program to find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. You must solve it without sorting the entire array.
Example 1
- Input: nums = [3,2,1,5,6,4], k = 2
- Output: 5
- Explanation:
- The array contains elements [3,2,1,5,6,4].
- If we sort the array: [1,2,3,4,5,6].
- The 2nd largest element is 5 (6 is 1st largest, 5 is 2nd largest).
- Therefore, the answer is 5.
- The array contains elements [3,2,1,5,6,4].
Example 2
- Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
- Output: 4
- Explanation:
- The array contains elements [3,2,3,1,2,4,5,5,6].
- If we sort the array: [1,2,2,3,3,4,5,5,6].
- The 4th largest element is 4 (counting from largest: 6,5,5,4).
- Therefore, the answer is 4.
- The array contains elements [3,2,3,1,2,4,5,5,6].
Constraints
- 1 ≤ k ≤ nums.length ≤ 10^5
- -10^4 ≤ nums[i] ≤ 10^4
- k is guaranteed to be valid
- Time Complexity: O(n) average case using quickselect
- Space Complexity: O(1) for iterative approach
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 the QuickSelect algorithm, which is based on QuickSort partitioning.
- Choose a pivot element and partition the array around it.
- If pivot position equals (n-k), then pivot is the kth largest element.
- If pivot position is greater than (n-k), search in the left subarray.
- If pivot position is less than (n-k), search in the right subarray.
- Continue until you find the element at position (n-k) from the start.