101 Logo
onenoughtone

Problem Statement

Element Rank Finder

You're analyzing a dataset and need to find the kth largest value without fully sorting the data.

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 the entire array?

Examples

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Explanation: The elements in descending order are [6,5,4,3,2,1]. The 2nd largest element is 5.

Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
Explanation: The elements in descending order are [6,5,5,4,3,3,2,2,1]. The 4th largest element is 4.

Constraints

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

Problem Breakdown

To solve this problem, we need to:

  1. The kth largest element is the element that would be at index k-1 in the array sorted in descending order
  2. We don't need to sort the entire array to find the kth largest element
  3. A min heap of size k can efficiently maintain the k largest elements
  4. The QuickSelect algorithm can find the kth largest element in O(n) average time
  5. Duplicate elements count as separate elements for ranking purposes
  6. This problem is a classic application of selection algorithms
ProblemSolutionCode
101 Logo
onenoughtone