Practice Problem

Kth Largest Element in an Array

Difficulty: Medium

Find the kth largest element in an unsorted array using a min-heap or quickselect algorithm.

Kth Largest Element in an Array

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

Examples

Example 1:

Input: nums = [3, 2, 1, 5, 6, 4], k = 2
Output: 5

Example 2:

Input: nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4
Output: 4

Example 3:

Input: nums = [1], k = 1
Output: 1

Constraints

  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

Expected Complexity

  • Time: O(n) average with Quickselect, or O(n log k) with Heap
  • Space: O(k) with Heap, O(1) with Quickselect (in-place)
MEDIUM
Heap
Min Heap
Priority Queue
Quickselect
Sorting
Intermediate

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium