Sort nearly sorted data with a small heap
Challenge · Write code · about 20 min
In values, every value is at most k cells away from its place in sorted order. Return the values sorted in ascending order.
Keep a min-heap of only k + 1 values: the smallest of the next k + 1 values must be the next output. Aim for O(n log k) time and O(k) extra memory.
Example 1
Input:
[[3,1,2,6,4,5,8,7],2]
Output:
[1,2,3,4,5,6,7,8]
The first output, 1, is among the first k + 1 = 3 values.
Example 2
Input:
[[2,1,4,3],1]
Output:
[1,2,3,4]
With k = 1 the heap holds two values at a time.
Constraints
- 0 ≤ values.length ≤ 10,000
- 0 ≤ k < max(1, values.length)
- Each value is at most k cells from its sorted position
Learn the idea first: Heap sort, a visual lesson.
More Heap sort problems
- Stability Warm-up
- State after two extractions Standard
- Implement heap sort Standard
- The k largest values Standard
- Spot the bug: the heap that never shrinks Standard