Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions day46/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
Question of the day: http://www.techiedelight.com/sort-k-sorted-array/

Given a k-sorted array, which is an array that is almost sorted, to the
point where each of the N elements in the array are at most `k` index
positions away from its correct sorted order, find an efficient
algorithm to sort the array.

## Ideas

Ignoring the interesting constraint, if we want to end up with a sorted
array, we can just use an efficient sorting algorithm such as merge sort
to sort the array and output it. An in-place merge sort would take `O(NlogN)`
time and `O(1)` space complexity.

Using the k-sorted constraint to our advantage, we can pick a better sort,
insertion sort which would run in `O(Nk)` time. For each element in the array,
check its `k` nearest neighbors to find the right place to insert it.

However, the best time complexity lies in a heap solution. If we start off
by creating a min heap of size `k+1`, we can iterate through the array by
popping the min element out of the heap and adding a new element into the
heap from the array. For each element, we do one pop from the heap and one
push onto the heap, both of which are `O(logk)` time complexity. The total
time complexity would therefore be `O(Nlogk)`. The difference in runtime
would especially be noticeable for larger values of `k`. The space required
to maintain the heap would be `O(k)` and the space we need to store the
resulting sorted array would come out to `O(N)`.

## Code

[Python](./sortKSortedArray.py)

## Follow up

28 changes: 28 additions & 0 deletions day46/sortKSortedArray.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from heapq import *

def sortKSortedArray(arr, k):
heap = arr[:k]
heapify(heap)

remaining = arr[k:]

result = []
for num in remaining:
# push num into the heap to maintain k+1 elements,
# then pop the min
result.append(heappushpop(heap, num))

while len(heap) > 0:
result.append(heappop(heap))

return result

def testSortKSortedArray():
assert sortKSortedArray([1,4,5,2,3,7,8,6,10,9], 2) == [1,2,3,4,5,6,7,8,9,10]
assert sortKSortedArray([2,1,3], 1) == [1, 2, 3]

def tests():
testSortKSortedArray()

if __name__ == "__main__":
tests()