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.