Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Heap (priority queue)

The k-th largest value

Medium · Target 15 minutes · Heap (priority queue) · Type asked atAmazonBloomberg

Given an array nums and an integer k, return the k-th largest value in the array. This is the k-th largest in sorted order, counting repeats: in [7, 7, 7] the second largest is 7.

Examples

InputOutputWhy
nums = [3, 2, 1, 5, 6, 4], k = 25Sorted descending: 6, 5, 4, …
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 44Repeats count: 6, 5, 5, 4.
nums = [-1, -5, -3], k = 1-1Negative values need no special case.

Constraints

  • 1 ≤ k ≤ n ≤ 10⁵
  • −10⁴ ≤ nums[i] ≤ 10⁴

Hints

Hint 1

Sorting works in O(n log n). What would you keep if you could only remember k numbers while reading the array once?

Hint 2

Keep the k largest values seen so far. Of those k, which one do you need to compare each new value against?

Hint 3

Store them in a min-heap: its top is the weakest of the k. A new value bigger than the top replaces it. At the end the top is the k-th largest.

Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.