KatInterview

Pick the Element at a Given Rank From the Top

Heaps, Sorting & SearchAuto-graded · 19 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapquickselectselection

Last updated

Find the k-th largest value in an unsorted integer list, counting duplicates separately, without necessarily sorting the whole list.

You are given an unsorted list of integers values and a positive integer rank. Return the value that would sit at position rank if the list were ordered from largest to smallest, where position 1 is the largest.

Equal values are counted as separate entries. For example, in [3, 3, 2] the 1st largest is 3, the 2nd largest is 3, and the 3rd largest is 2.

A full sort is a valid baseline, but try to do better: a bounded-size heap or a partition-based selection avoids ordering the entire list.

Your function should not depend on the input being sorted, and it may be given negative numbers and repeated values.

Constraints

  • 1 <= rank <= len(values)
  • values contains at least one integer
  • Each value is a (possibly negative) integer that fits in a standard 32-bit signed range
  • The returned value is a single integer taken from values

Examples

Example 1

Input: kth_from_top([3, 2, 1, 5, 6, 4], 2)

Output: 5

Example 2

Input: kth_from_top([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)

Output: 4

Example 3

Input: kth_from_top([7], 1)

Output: 7

Hints

Hint 1

Think about what the answer would be if the list were sorted in descending order. Which index would you read?

Hint 2

You only need to track the `rank` largest values seen so far. Which heap type lets you cheaply discard the smallest of those?

Hint 3

Keep a min-heap of size `rank`. For each remaining number, if it beats the heap's root, replace the root. After one pass, the root is the answer. Quickselect is an alternative with O(n) expected time.