Problem 465126 · easy · Level 04 Non-Linear Data Structures

Parcels That Arrived Slightly Out of Order

heaps · sorting · sliding heap

Parcels come off a conveyor belt in an order that is almost right: every parcel number in nums is at most k places away from where it would stand in fully sorted order. Return the parcel numbers in ascending order.

A full O(n log n) sort would work, but the guarantee lets you do better: aim for O(n log k).

Examples

Input:  nums = [3, 1, 2, 6, 4, 5, 9, 7, 8], k = 2
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation: 3 is at index 0 but belongs at index 2, a displacement of 2 = k.

Input:  nums = [1, 2, 3], k = 0
Output: [1, 2, 3]

Constraints

  • 0 <= len(nums) <= 10**5, 0 <= k < len(nums) (or k = 0 for an empty list)
  • Every element is guaranteed to be within k positions of its sorted position.
  • Target complexity: O(n log k).

Goals

  • Exploit a bound on how far elements are displaced
  • Keep a heap of bounded size while streaming through the input
  • Emit elements in sorted order faster than a full sort
Starting Python…