Bounded heap · Medium
A batch report shows the largest k recorded amounts in descending order. Equal values still represent separate entries and occupy separate slots. The batch can be large while the result is small, so retaining a second full sorted copy is outside the extra-memory target.
Return the largest min(k,n) values in descending numeric order while retaining duplicate occurrences and using only bounded extra storage.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], k: integer }
Fields
- nums is an unsorted batch of integer amounts; k is the requested result size.
Output
Return value
- Return values, not indexes or distinct values. Equal entries count separately.
- k = 0 returns []; k greater than the batch size returns all values descending.
Constraints
- 0 <= nums.length <= 100000; values are signed integers between -1000000000 and 1000000000.
- 0 <= k <= 100001.
Examples
Example 1
{
"k": 3,
"nums": [
3,
8,
8,
1
]
}Returns
[
8,
8,
3
]Example 2
{
"k": 4,
"nums": [
-1,
2
]
}Returns
[
2,
-1
]Required complexity
O(n log(k + 1) + k log(k + 1)) time and O(min(n,k) + 1) auxiliary space