← All Exercises
K Largest Elements with heapq
basicpython
Background
Heap-based selection is used for leaderboards, monitoring top endpoints, and streaming analytics where k is much smaller than n.
Problem
Given a list of integers and a non-negative integer k, return the k largest values in descending order without sorting the entire list.
Input
A list of integers and an integer k with 0 <= k <= len(nums).
Output
A list of at most k integers in non-increasing order.
Sample tests
Sample 1
Input: nums = [3,1,5,12,2,11], k = 3
Expected: [12, 11, 5]
Sample 2
Input: nums = [4,4,4], k = 2
Expected: [4, 4]
Sample 3
Input: nums = [1,2], k = 0
Expected: []
Your solution
Learning objective
Use the heapq library for bounded selection and understand why a size-k heap beats a full sort.