Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing

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.

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.

Requirements

  • Duplicates count separately.

Constraints

  • 1 <= k <= len(nums).
  • Up to 1,000,000 values.
  • Values may repeat and may be negative.

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.