MediumArrayDivide and ConquerSortingHeap (Priority Queue)Quickselect

1 approach, code in every language

Problem description

You are given an integer array `nums` and an integer `k`.

Return the `k`-th largest element in the array. Note that this is the `k`-th largest element in sorted order, not the `k`-th distinct element — duplicate values each count toward the ranking.

Aim to solve it without fully sorting the array.

Example 1

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

Output: 5

Sorted in descending order the array is [6,5,4,3,2,1], so the 2nd largest value is 5.

Example 2

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

Output: 4

Sorted descending it is [6,5,5,4,3,3,2,2,1]; the 4th entry is 4.

Constraints

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

After the pattern

Now solve one you haven't seen.

Kth Highest Daily Swing is our own problem on the technique behind Kth Largest Element in an Array: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free