2

In the familiar problem where every element in an array is at most k positions away from it's correct location, either to the left or to the right, the min-heap implementation is as follows.

Create a min-heap of size k+1. So, the root of the min heap is the smallest element of the sorted array. For the remaining n-(k+1) elements, in each iteration, the choice is between a[i] and the elements that are already in heap. So insert a[i] in to the heap, heapify, and do extract min. This will keep populating the a[i-k] elements of the sorted array.

Time complexity : O(k) + O(n-k).log(k)

Space complexity : O(k)

My question is : Can this be done using O(1) space complexity?

I found an approach here, but could not sense of it. Could someone elaborate?

You can do this in-place. Start from the far end, and use a max-heap instead of a min-heap. Heapify that final block of 2k elements in-place. Store the first extracted element in a variable; subsequent elements go in the positions vacated immediately before the final block of 2k (which contains the heap structure), similar to regular heapsort. When only 1 block remains, heapsort it in place. A final O(n) pass is needed to "rotate" the final block back to the initial block. The rotation is not trivial but can be done in O(n) and O(1) space.

Community
  • 1
  • 1
user121
  • 305
  • 1
  • 3
  • 9

1 Answers1

1

The basic idea is to store the heap in the array, use it to sort the remaining elements of the array, and then sort the heap portion itself.

Here is a variant using a min-heap that might be easier to understand.

  1. Heapify the first k+1 elements of the array, in place. The minimum element of the heap will be the minimum of the entire array.

    k+1  | n-(k+1)
    heap | unsorted
    
  2. Swap the minimum element of the heap with the first element of the unsorted portion and re-heapify.

    k+1  | 1      | n-(k+2)
    heap | sorted | unsorted
    
  3. Repeat step 2 until there are no more unprocessed elements. At this point the heap contains the k+1 largest elements of the array, and the remaining elements are in sorted order.

    k+1  | n-(k+1)
    heap | sorted
    
  4. Sort the heap portion of the array

    k+1         | n-(k+1)
    sorted heap | sorted
    
  5. Move the sorted heap to the other end of the array. The array is now sorted.

    n-(k+1)| k+1
    sorted | sorted heap
    
augurar
  • 12,081
  • 6
  • 50
  • 65