Top k largest elements
Given an integer array nums and an integer k, return the k largest elements of nums. You may return them in any order.
The result is a multiset. If a value appears several times and those copies fall inside the top k, include each copy.
Implement:
def top_k_largest(nums: list[int], k: int) -> list[int]:
...
Constraints
0 <= len(nums) <= 10^6-10^9 <= nums[i] <= 10^9-
0 <= k. Ifkis 0, return an empty list. Ifk >= len(nums), return every element. - Do better than sorting the whole array when
kis much smaller thann.
Example 1
nums = [4, 9, 1, 7, 3], k = 2
output: [9, 7] # [7, 9] is also accepted
Example 2
nums = [5, 5, 2, 5, 1], k = 2
output: [5, 5] # duplicates are counted separately
Be ready to discuss what changes if nums arrives as a stream that is too large to keep in memory.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.

