Kth largest element

Python data engineering interview problem. Difficulty: intermediate. Pattern: Heaps. About 14 minutes. Part of the Pro drill bank.

Find the kth largest value in an unsorted list where duplicates count separately. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

A large metric stream needs only one rank, not a complete sorted copy of millions of values. Return the kth largest value, counting duplicates as separate positions. A min-heap of size k can keep only the candidates that still matter. Write kth_largest(nums: list[int], k: int) -> int. When sorted descending, [3,2,3,1,2,4,5,5,6] is [6,5,5,4,...], so the fourth largest is 4. The starter file already contains the function name, harness and print lines. Keep them and fill only the function body.

Requirements

  • Count duplicate values separately.
  • Return the value at rank k from the largest end.
  • Respect the supplied valid k range.

Constraints

  • nums is unsorted and k is from 1 to len(nums).
  • Return one integer.

Examples

Input: kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) Output: 4 Sorted descending: 6, 5, 5, 4, 3, 3, 2, 2, 1. The 4th value is 4.

Topics: lakebench, python, top-k, priority queue.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Kth largest element

Interview-style drill: Find the kth largest value in an unsorted list where duplicates count separately.

Implement `kth_largest(nums: list[int], k: int) -> int`. Return the kth largest element of `nums` when the list is sorted in descending order. Duplicates count separately: in `[5, 5, 4]` the 2nd largest is `5`. `k` is between 1 and `len(nums)`. The list can hold millions of values and `k` can be small, so avoid sorting the whole list when you can.