KatInterview

Find the K-th Largest Element Without Using a Heap

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchquickselectpartitioningselection-algorithms

Last updated

Tests implementation of quickselect to find the k-th largest value in an unsorted array, treating duplicates as separate elements.

You're analyzing a stream of numerical measurements that arrive in arbitrary order. Write a function that identifies the k-th largest measurement from the collection.

Your function receives a list of integer measurements and a position k, then returns the k-th largest value. Duplicate measurements are treated as distinct entries—if three readings all show 100, they occupy three separate positions when ranked from largest to smallest.

Important constraint: You may not use any heap or priority queue data structure (including Python's heapq module) in your solution.

Function Signature

def find_kth_largest(nums: list[int], k: int) -> int:

Parameters

  • nums: A list of integer measurements in the order they were recorded
  • k: The position to find (1-indexed), where k=1 means the largest value, k=2 means the second-largest, etc.

Return Value

The integer value at the k-th position when all measurements are ranked from largest to smallest.

Constraints

  • 1 <= k <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • k is guaranteed to be valid (never exceeds the length of nums)

Examples

Example 1

Input: find_kth_largest([70, 20, 90, 40, 90, 10], 2)

Output: 90

Example 2

Input: find_kth_largest([70, 20, 90, 40, 90, 10], 4)

Output: 40

Example 3

Input: find_kth_largest([-50, 0, -50, 30], 3)

Output: -50

Hints

Hint 1

Consider selection algorithms that find a specific rank without fully sorting the entire array

Hint 2

A partition-based approach can eliminate portions of the array that definitely don't contain your target rank

Hint 3

When many duplicate values exist, a three-way partition (less than, equal to, greater than) avoids redundant work compared to a two-way split