Top N Elements Without Full Sort

Hard ⏱ 18 min 26% acceptance ★★★★☆ 4.4
Write top_n(numbers, n) that returns the n largest values from numbers, sorted descending, without calling <code>sorted()</code> or <code>.sort()</code> on the whole list. Instead, repeatedly find and remove the current maximum n times (selection-style). If n exceeds the list length, return all elements sorted descending.

Examples

Example 1
Input
numbers = [5, 1, 9, 3, 7], n = 3
Output
[9, 7, 5]
Explanation

The three largest values, largest first.

Constraints

  • 0 <= n
  • 0 <= len(numbers) <= 10^4

Topics

ListsSelection

Companies

NetflixAmazon

Hints

Hint 1

Work on a copy of the list so the caller's list is untouched.

Hint 2

Use max() to find the current largest, record it, then remove one occurrence with .remove().

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.