Kth Largest Element in an Array - Problem
Given an integer array nums and an integer k, return the k-th largest element in the array.
Note that it is the k-th largest element in the sorted order, not the k-th distinct element.
Can you solve it without sorting?
Input & Output
Example 1 — Basic Case
$
Input:
nums = [3,2,1,5,6,4], k = 2
›
Output:
5
💡 Note:
The array sorted in descending order is [6,5,4,3,2,1]. The 2nd largest element is 5.
Example 2 — Different K
$
Input:
nums = [3,2,3,1,2,4,5,5,6], k = 4
›
Output:
4
💡 Note:
The sorted array is [6,5,5,4,3,3,2,2,1]. The 4th largest element is 4.
Example 3 — Minimum Size
$
Input:
nums = [1], k = 1
›
Output:
1
💡 Note:
There's only one element, so the 1st largest is 1.
Constraints
- 1 ≤ k ≤ nums.length ≤ 105
- -104 ≤ nums[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [3,2,1,5,6,4] and k=2
2
Find Position
Use partitioning to locate 2nd largest position
3
Output
Return the element at k-th largest position: 5
Key Takeaway
🎯 Key Insight: Use partitioning techniques like Quickselect to find the k-th element in O(n) average time instead of O(n log n) sorting
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code