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
Kth Largest Element in an Array INPUT nums array: 3 i=0 2 i=1 1 i=2 5 i=3 6 i=4 4 i=5 k = 2 Find 2nd largest element in array If sorted: [1,2,3,4,5,6] 2nd from end = 5 ALGORITHM (QuickSelect) 1 Pick Pivot Choose last element: 4 2 Partition Array Elements > pivot go left 6 5 4 3 2 1 >4 pivot <=4 3 Check Pivot Position Pivot at index 2 Need k-1 = 1 for 2nd 4 Recurse Left Search in [6,5] Partition gives: 5 Time: O(n) average Space: O(1) in-place FINAL RESULT After QuickSelect partitioning: 6 1st 5 2nd 4 3rd 3 2 1 OUTPUT 5 OK - 2nd largest is 5 (6 > 5 > 4 > 3 > 2 > 1) No Sorting Required! Key Insight: QuickSelect uses partitioning like QuickSort but only recurses into ONE side containing the kth element. This reduces average time from O(n log n) sorting to O(n). The pivot's final position tells us its rank! TutorialsPoint - Kth Largest Element in an Array | QuickSelect Approach (Optimal)
Asked in
Facebook 65 Amazon 58 LinkedIn 42 Apple 38 Google 35
78.0K Views
High Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen