Final challenge: top-k, k lists and the median
After this: Use a heap on three well-known interview problems.
This challenge uses a heap on three well-known interview problems. Each step is scored on its own. First, you predict what a function prints when it finds the largest values in a list. Second, you pick the best way to merge several sorted lists into one, and say what it costs. Third, you choose the structure that can report the middle value of a growing list of numbers.
Everything you need is in the six lessons. You can try each step as many times as you like, and hints work as they do in the lessons.
Step 1 of 3Top-k
Top-k
Find the three largest of [4, 9, 1, 7, 3, 8]. What does the last line print: the heap array, then its root?
import heapq
def top_k(values, k): heap = [] # a min-heap of the k largest seen so far for v in values: heapq.heappush(heap, v) if len(heap) > k: heapq.heappop(heap) # drop the smallest: it cannot be in the top k return heap
heap = top_k([4, 9, 1, 7, 3, 8], 3)print(heap, heap[0]) # the root is the k-th largestint[] values = {4, 9, 1, 7, 3, 8};int k = 3;PriorityQueue<Integer> heap = new PriorityQueue<>(); // a min-heap of the k largest seen so farfor (int v : values) { heap.add(v); if (heap.size() > k) heap.poll(); // drop the smallest: it cannot be in the top k}System.out.println(heap + " " + heap.peek()); // the root is the k-th largestMerge k sorted lists
You have k sorted lists with n items in total, and you want one sorted list. What is the heap approach, and what does it cost?
Running median
Numbers arrive one at a time. After each one you must report the median of everything so far: the middle value once they are in order. Which structure do you use, and what is the cost per number?
- Keep the k largest with a min-heap of size k, merge k sorted lists in O(n log k), and report a running median with two heaps.