diff --git a/day47/README.md b/day47/README.md new file mode 100644 index 0000000..837943e --- /dev/null +++ b/day47/README.md @@ -0,0 +1,35 @@ +Question of the day: http://www.techiedelight.com/find-kth-smallest-element-array/ + +Given an array and positive integer `k`, find kth smallest element +in the array. + +Example: + +arr = [7, 4, 6, 3, 9, 1] +k = 3 + +Output: + +4 + +## Ideas + +1) Sort the array in `O(nlogn)` time and then access the kth index of the + array to get the answer. + +2) Min-heapify the array in `O(n)` time and then pop from the min heap `k` + times in `O(klogn)` time. Overall runtime `O(n + klogn)`. + +3) Max-heapify the first `k` elements of the array in `O(k)` time and then + repeatedly remove the max element, replacing it with a new element from + the input array, until there are no more unused elements from the input + array in `O(nlogk)` time. Once there are no more elements, the root in + the max heap will be the kth smallest element of the input array. + +Let's implement all three. + +## Code + +[Python](./day47.py) + +## Follow up diff --git a/day47/findKSmallestInArray.py b/day47/findKSmallestInArray.py new file mode 100644 index 0000000..f35dbc4 --- /dev/null +++ b/day47/findKSmallestInArray.py @@ -0,0 +1,53 @@ +import heapq + +def efficientSortIdea(arr, k): + return sorted(arr)[k-1] + +def minHeapIdea(arr, k): + heapq.heapify(arr) + last = arr[0] + while k > 0: + last = heapq.heappop(arr) + k -= 1 + return last + +def maxHeapIdea(arr, k): + # negate values when adding into python's min-heap implementation + arr = map(lambda x: -x, arr) + h = arr[:k] + heapq.heapify(h) + for num in arr[k:]: + heapq.heappushpop(h, num) + return -heapq.heappop(h) + +def testEfficientSortIdea(): + assert efficientSortIdea([1, 2, 3, 4, 5], 3) == 3 + assert efficientSortIdea([3, 1, 4, 2, 5], 3) == 3 + assert efficientSortIdea([5, 4, 3, 2, 1], 3) == 3 + assert efficientSortIdea([4, 2], 1) == 2 + assert efficientSortIdea([1, 9, 2, 7, 4, 6, 4, 2, 1, -1, -5, -9], 5) == 1 + assert efficientSortIdea([-3, -6, 1, 0, 1], 4) == 1 + +def testMinHeapIdea(): + assert minHeapIdea([1, 2, 3, 4, 5], 3) == 3 + assert minHeapIdea([3, 1, 4, 2, 5], 3) == 3 + assert minHeapIdea([5, 4, 3, 2, 1], 3) == 3 + assert minHeapIdea([4, 2], 1) == 2 + assert minHeapIdea([1, 9, 2, 7, 4, 6, 4, 2, 1, -1, -5, -9], 5) == 1 + assert minHeapIdea([-3, -6, 1, 0, 1], 4) == 1 + +def testMaxHeapIdea(): + assert maxHeapIdea([1, 2, 3, 4, 5], 3) == 3 + assert maxHeapIdea([3, 1, 4, 2, 5], 3) == 3 + assert maxHeapIdea([5, 4, 3, 2, 1], 3) == 3 + assert maxHeapIdea([4, 2], 1) == 2 + assert maxHeapIdea([1, 9, 2, 7, 4, 6, 4, 2, 1, -1, -5, -9], 5) == 1 + assert maxHeapIdea([-3, -6, 1, 0, 1], 4) == 1 + +def tests(): + testEfficientSortIdea() + testMinHeapIdea() + testMaxHeapIdea() + +if __name__ == "__main__": + tests()