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
35 changes: 35 additions & 0 deletions day47/README.md
Original file line number Diff line number Diff line change
@@ -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
53 changes: 53 additions & 0 deletions day47/findKSmallestInArray.py
Original file line number Diff line number Diff line change
@@ -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()