Streaming kth Largest Element

Coding
Heaps
Medium
You need the kth largest element while streaming n values and k is small. What data structure naturally supports O(n log k) processing?
Hint 1

Keep only the k largest values seen so far, discarding anything smaller than the smallest of those k.

Hint 2

A heap lets you find and remove the current minimum of the kept set quickly.

Show worked solution
  1. 1. Maintain a bounded min-heap

    Keep a min-heap holding the largest elements seen so far; the heap's root is always the smallest of these elements.

  2. 2. Process each new element

    For each new value, compare it to the heap's root; if larger, replace the root and re-heapify. Each of the elements costs , giving total.

Answer: A min-heap of size k.

Related roles: Browse quant jobs

Related problems